/*
Script created by SQL Compare from Red Gate Software Ltd at 1/14/2008 2:09:14 PM
Run this script on PHSSQL176.Insight_Conversion_Test_22_Vss to make it the same as PHSSQL176.Insight_Conversion_test
Please back up your database before running this script
*/
SET NUMERIC_ROUNDABORT OFF
GO
SET ANSI_PADDING, ANSI_WARNINGS, CONCAT_NULL_YIELDS_NULL, ARITHABORT, QUOTED_IDENTIFIER, ANSI_NULLS ON
GO
IF EXISTS (SELECT * FROM tempdb..sysobjects WHERE id=OBJECT_ID('tempdb..#tmpErrors')) DROP TABLE #tmpErrors
GO
CREATE TABLE #tmpErrors (Error int)
GO
SET XACT_ABORT ON
GO
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
GO
BEGIN TRANSACTION
GO
PRINT N'Dropping [dbo].[InsertNewAnimalProtocolSubmissions]'
GO
DROP PROCEDURE [dbo].[InsertNewAnimalProtocolSubmissions]
GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Dropping [dbo].[UpdateAnimal_ProtocolSubmissionStagingData]'
GO
DROP PROCEDURE [dbo].[UpdateAnimal_ProtocolSubmissionStagingData]
GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Dropping [dbo].[fnGetProgramDirector]'
GO
DROP FUNCTION [dbo].[fnGetProgramDirector]
GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Creating [dbo].[GetLogItems]'
GO
SET QUOTED_IDENTIFIER OFF
GO
/******************************************************************
* Name:			GetLogItems
* Purpose:		Retrieves the LogItem for the given ProtocolProcessId
*					
*
* PARAMETERS
* Name    				Description					
* -------------  		----------------------------------
* @protocolProcessId			ProtocolProcessId for the LogItem
******************************************************************/

CREATE PROCEDURE [dbo].[GetLogItems]
(
@protocolProcessId	int			
)
AS
BEGIN

	SET NOCOUNT ON

			Select	[Id],
				[ProtocolProcessId], 
				[QuestionnaireVersionId],
				[QuestionnaireAnswerId],
				[Type],
				[Category],
				[QuestionName],
				[Answer],
				[Description],
				[Completed]
				
					
			FROM LogItem 

			WHERE [ProtocolProcessId] = @protocolProcessId  
	
END


GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Creating [dbo].[spFdsCNCreatePerEmployeeJobMap]'
GO


/******************************************************************************
**		VSS File: $/spFdsCNCreatePerEmployeeJobMap.sql 
**		Name: spFdsCNCreatePerEmployeeJobMap	
**		Desc: 	This procedure creates a record in the 
**				PerHRDepartment table
**			
**		Return values: None
** 
**		Called by:   
**			
*******************************************************************************
**		Change History
*******************************************************************************
**		Date:		Author:				Description:
**		--------	--------			---------------------------------------
**	
*******************************************************************************/
CREATE Procedure dbo.spFdsCNCreatePerEmployeeJobMap (
	/* Param List */
	@admInternalPersonId		int,
	@perJobTypeId				int,
	@perHRDepartmentId			int,
	@recordNumber				int,
	@perEmployeeStatusTypeId	int,
	@standardHours				VARCHAR(64),
	@hourlyRate					numeric(17,4)
)	
AS	
BEGIN 

	SET NOCOUNT ON

	DECLARE @_errorCode			INT
	DECLARE @_isTracked			INT

	SET @_errorCode  = 0

	-- Set is Tracked to true
	SET @_isTracked = 1

	-- Insert the PerEmployee_Job_Map
	INSERT INTO PerEmployee_Job_Map
					(
						AdmInternalPersonId,
						PerJobTypeId, 
						PerHRDepartmentId,
						RecordNumber,
						PerEmployeeStatusTypeId,
						StandardHours,
						HourlyRate,
						IsTracked
					)
	VALUES			(
						@admInternalPersonId,	
						@perJobTypeId,	
						@perHRDepartmentId,
						@recordNumber,		
						@perEmployeeStatusTypeId,
						@standardHours,
						@hourlyRate,
						@_isTracked
					)

	SET @_errorCode = @@ERROR

	IF @_errorCode <> 0 BEGIN
		RAISERROR('Unable to create PerEmployeeJobMap record for InternalPerson %s', 16, 1, @admInternalPersonId)
		RETURN @_errorCode
	END

END


GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Creating [dbo].[spFdsNCompleteFeed]'
GO
SET QUOTED_IDENTIFIER ON
GO

/***************************************************************************
* Name:			spFdsNStartFeed
* Purpose:		Used to complete an instance of a feed
*
*
* PARAMETERS
* Name					Description					
* -------------			-----------------------------------------------------------
* @_FeedInstanceId	
* @_FeedStatusTypeId	
*
* ERRORS USED		Description
* -------------		-----------------------------------------------------
* n/a
*
* RETURN VALUE
* Value    			Description					
* --------------	------------------------------------------------------
*	0				Succeeded
*	1				Failed
***************************************************************************/

CREATE PROCEDURE dbo.spFdsNCompleteFeed (
	@_FeedInstanceId integer 
	,@_FeedStatusTypeId integer
)
AS
BEGIN
	SET NOCOUNT ON

	DECLARE @FEED_SUCCESS	Integer
	Set @FEED_SUCCESS = 2
	DECLARE @FEED_FAILED	Integer
	Set @FEED_FAILED = 3

	/*
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	The feed status can only be set to failed or success, otherwise stop here
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	*/
	If @_FeedStatusTypeId <> @FEED_FAILED and @_FeedStatusTypeId <> @FEED_SUCCESS
		return 1

	/*
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	Complete the feed
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	*/
	Update
		SvcFeedRun
	Set
		SvcFeedStatusTypeId = @_FeedStatusTypeId
		,EndDate = getdate()
	Where
		[Id] = @_FeedInstanceId

	SET NOCOUNT OFF

	return 0

END

GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Altering [dbo].[GetWorkflowExecutionDetails]'
GO
/************************************************************************************************        
* Name:  [GetWorkflowExecutionDetails]                                                                  
* Purpose: This stored procedure gets the email generated(scrapped form chunk of data) having the       
*     passed in executionId       
*        
*          
* PARAMETERS          
* Name   Description        
* ------------------------- -----------------------------        
* @ExecutionId    Workflow execution Id        
*        
************************************************************************************************        
*Call: [GetWorkflowExecutionDetails] 6        
************************************************************************************************/
ALTER procedure [dbo].[GetWorkflowExecutionDetails] 
(        
 @executionId int         
) 
as        
begin        
set nocount on  
  
DECLARE @hourDiff int       
 set @hourDiff = (select datediff(hour, getdate(), getutcdate())) * -1          
 DECLARE @Email TABLE (                      
    [ExecutionDetailsId] INT,                    
    [EmailDescription] nvarchar(max)                    
    )                      
    Insert Into @Email([ExecutionDetailsId],[EmailDescription]) EXEC [dbo].[GetWFEMailDecription] @executionId       
   
  If exists (Select 1 from @Email)  
     BEGIN             
	  Select  swd.[ActionName],          
	  DATEADD(hh,@hourDiff,swd.[StartedOn]) as StartedOn,          
	  swd.[outPut],          
	  swd.[ActionType],          
	  swl.[Description] as [ActivityDescription],          
	  rtrim(ltrim(adp.LastName)) +', '+rtrim(ltrim(adp.FirstName)) as FullName,     
	  fwku.UserName,          
	  DATEADD(hh,@hourDiff,swd.[LastUpdatedDateTime])as[ExecutionEndDate],      
	  swl.[Comments] as [Comments],      
	  email.EmailDescription      
	          
	  from swexecutionDetails  swd          
	  left join swactivitylist swl           
	  On swd.ActionName = swl.ActivityName          
	  and swl.ExecutionId = swd.ExecutionId          
	  left join swvirtualUser swvu          
	  On swvu.Id = swl.VirtualuserId          
	  Left join fwkDomainUser fwku          
	  On fwku.Id= swvu.UserId --adp.FwkDomainUserId      
	  Left join admperson adp          
	  On adp.FwkDomainUserId = Fwku.Id       
	  left join @Email email      
	  On email.ExecutionDetailsId = swd.[Id]      
	  where swd.executionid= @executionId          
	  order by swd.[StartedOn]
     END
END

GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Altering [dbo].[GetClinicalTrialBudgetFeedData]'
GO




ALTER PROCEDURE [dbo].[GetClinicalTrialBudgetFeedData]( @institution varchar(256) )
AS
BEGIN
   SET NOCOUNT ON
   If @institution = 'ClinicalTrialBudgetInstitutionMGH'
      BEGIN
        SELECT Dept, Description, Price, ChargeCode, CPTCode, ((Price * ResearchRate)/100) AS 'ResearchCharge', Location   
		FROM mgh_cdmfeed 
		WHERE description is not null 
			and description <> ''
		ORDER BY Description
      END
   Else If @institution = 'ClinicalTrialBudgetInstitutionBWH'
      BEGIN
        SELECT Dept as 'Dept', Description as 'Description', Price as 'Price', ChargeCode as 'ChargeCode', CPTCode as 'CPTCode', (IndustryRate * Price) as 'ResearchCharge', Location
		FROM bwh_cdmfeed 
		WHERE description is not null 
			and description <> ''
		ORDER BY Description
      END
END




GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Altering [dbo].[CloneClinicalTrialBudgetExpense]'
GO
ALTER PROCEDURE [dbo].[CloneClinicalTrialBudgetExpense]
(
  @budgetId int, 
  @budgetIdNew int 
) 
AS 
BEGIN

------------------------------
--EXPENSES
----------------------------
INSERT INTO ClinicalTrialBudgetExpense (ClinicalTrialBudgetId, StudyCostCode, OtherExpenseText, ExpenseCost, VariableCost, ApplyOverhead) SELECT @budgetIdNew, StudyCostCode, OtherExpenseText, ExpenseCost, VariableCost, ApplyOverhead FROM clinicaltrialbudgetexpense where ClinicalTrialBudgetId = @budgetId
----------------------------

 IF (@@ERROR <> 0)
      BEGIN
        RAISERROR ('Failed to clone clinical trial budget. Error = %s.', 16, 1, @@ERROR)
      RETURN
 END
END



GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Creating [dbo].[GetDatabaseVersion]'
GO

create procedure GetDatabaseVersion
as
begin
	set nocount on
	select TOP 1 VersionName from Version ORDER BY Id DESC
end



GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Altering [dbo].[InjectSubContractorFromInfoEd]'
GO
 /***************************************************************************                  
* Name:   InjectSubContractorFromInfoEd                  
* Purpose:  Using table Stg_IE_AgrSubContractor, insert all the new records.                  
***************************************************************************/                  
ALTER PROCEDURE [dbo].[InjectSubContractorFromInfoEd]                  
AS                  
BEGIN                  
SET NOCOUNT ON                  

INSERT AgrSubContractor                   
 ([Name]  
  ,[InfoEdInstCode]  
      ,[Description]  
      ,[AdmSponsorId]  
   ,[SubcontractorPIName]   )  
              
   SELECT         
     isnull ([Name], '')
  ,InfoEdInstCode     
 ,Description             
     ,AdmSponsorId     
    ,[PIName]              
  FROM STG_IE_AgrSubContractor             
  where  InfoEdInstCode   not in (select InfoEdInstCode from AgrSubContractor)       

                

                  
 SET NOCOUNT OFF                  
                  
END 

GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Creating [dbo].[spFdsNInsertErrorRow]'
GO
SET QUOTED_IDENTIFIER OFF
GO

/******************************************************************
*$Archive: /PHSRAG/Applications/WebApplications/Insight_2.2.0/Database/MissingStoredProcs/SPsMissingFrom220VSS.sql $
*
* Name:					spFdsNInsertErrorRow
* Purpose:				Creates a new entry in the FdsErrors table.
*
* PARAMETERS
* Name    				Description					
* -------------  		-----------------------------------------------
* @svcFeedRunId			Id of the particular Feed Run
* @packageName			Name of the package that failed
* @taskName				Name of the task taht failed
* @errorTypeId			Type of error
* @data					XML data
* @status				Status, usually OPEN
*
* ERRORS USED		Description
* -------------		-------------------------------------------
*
* RESULT SET
* Name					Description		
* -------------  		-----------------------------------------------
* None
*
* RETURN VALUE
* Value    				Description					
* -------------  		-----------------------------------------------
* None
*
***********************************************************************/

CREATE Procedure spFdsNInsertErrorRow
(
	--SvcFeedRunId, TaskName, ErrorTime, ErrorTypeId, Data, Status 
	@svcFeedRunId		AS INTEGER,
	@packageName		AS VARCHAR(100),
	@taskName			AS VARCHAR(100),
	@errorTypeId		AS INTEGER,
	@data				AS TEXT,
	@status				AS VARCHAR(50)
)
AS

BEGIN
	SET NOCOUNT ON

	BEGIN
		INSERT INTO FdsErrors ( 
				SvcFeedRunId, 
				PackageName,
				TaskName, 
				ErrorTime, 
				ErrorTypeId, 
				Data, 
				Status ) 
		VALUES (@svcFeedRunId,
				@packageName,
				@taskName,
				GETDATE(),	
				@errorTypeId,
				@data,	
				@status )
			
		IF @@ERROR <> 0 BEGIN
            RAISERROR('Unable to create error record for feed: %s', 16, 1, @svcFeedRunId)
        END
	END
		
END

GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Altering [dbo].[CloneClinicalTrialBudget]'
GO
SET QUOTED_IDENTIFIER ON
GO
--Takes a budgetid to be cloned and returns the budgetIdnew to be used in cloning the other clinical trial
--budget objects 

ALTER PROCEDURE [dbo].[CloneClinicalTrialBudget]
(
  @budgetId int,
  @budgetIdNew int
) 
AS 
BEGIN
--BUDGET

-----------------------
INSERT INTO  ClinicalTrialBudget ( StatusCode, PIPersonId, OriginatorPersonId, StudyShortTitle, 
            StudyFullTitle, SponsorId, SponsorProtocolNumber, StudyType, OtherType, PIInitiated, 
            OverheadRateCode, OtherNegotiatedRate, SubjectVisits, PrimaryStudyLocationCode, InstitutionCode,
            EnrolledSubjects, IRBProtocolNumber, FolderNumber, InsertedDate, LastModifiedDate, FwkResourceId ) SELECT StatusCode, PIPersonId, OriginatorPersonId, StudyShortTitle, 
            StudyFullTitle, SponsorId, SponsorProtocolNumber, StudyType, OtherType, PIInitiated, 
            OverheadRateCode, OtherNegotiatedRate, SubjectVisits, PrimaryStudyLocationCode, InstitutionCode,
            EnrolledSubjects, IRBProtocolNumber, FolderNumber, InsertedDate, LastModifiedDate, FwkResourceId  FROM clinicaltrialbudget where Id = @budgetId
	SET @budgetIdNew = IDENT_CURRENT('clinicaltrialbudget')
-------------------------


SELECT @budgetIdNew
 IF (@@ERROR <> 0)
      BEGIN
        RAISERROR ('Failed to clone clinical trial budget. Error = %s.', 16, 1, @@ERROR)
      RETURN
 END
END 












GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Creating [dbo].[sp_dts_addlogentry]'
GO
CREATE PROCEDURE [dbo].[sp_dts_addlogentry]  @event sysname,  @computer nvarchar(128),  @operator nvarchar(128),  @source nvarchar(1024),  @sourceid uniqueidentifier,  @executionid uniqueidentifier,  @starttime datetime,  @endtime datetime,  @datacode int,  @databytes image,  @message nvarchar(2048)AS  INSERT INTO sysdtslog90 (      event,      computer,      operator,      source,      sourceid,      executionid,      starttime,      endtime,      datacode,      databytes,      message )  VALUES (      @event,      @computer,      @operator,      @source,      @sourceid,      @executionid,      @starttime,      @endtime,      @datacode,      @databytes,      @message )  RETURN 0
GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Creating [dbo].[GetEMailTemplate]'
GO
/******************************************************************  
* Name:   GetEMailTemplate  
* Purpose:  Retrieves the email template with the specified type  
*  
* PARAMETERS  
* Name         Description       
* -------------      -------------------------------------------  
*      
******************************************************************/  
  
CREATE Procedure [dbo].[GetEMailTemplate]   
@type VARCHAR(50),  
@moduleType VARCHAR(256)  
AS  
BEGIN  
  
 SET NOCOUNT ON  
  
  Select Id,  
   Type,  
   RefCode.RefMeaning as TypeMeaning,  
   BodyText,
   [Subject]  
  FROM EMailTemplate LEFT JOIN RefCode ON EMailTemplate.Type = RefCode.RefCode  
  WHERE type = @type  
   AND ModuleType = @moduleType  
  ORDER BY TypeMeaning  
   
END  
  
  

GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Altering [dbo].[UpdateEmailAddress]'
GO

/******************************************************************
* VSS File Path: $Archive: /PHSRAG/Applications/WebApplications/Insight_2.2.0/Database/MissingStoredProcs/SPsMissingFrom220VSS.sql $
* Name:  UpdateEmailAddress
* Purpose:  
* Updates email information.
*
* PARAMETERS
* Name    				Description					
* -------------  		---------------------------------------
* @emailAddressId		The email address id. (PK)
* @emailAddress 		The email address.
*
* RESULT SET
* Name    			Description					
* --------------	-------------------------------------------
* N/A				n/a
*
*
* RETURN VALUE
* Value    			Description					
* --------------	-------------------------------------------
* N/A				N/A
*
******************************************************************/
ALTER Procedure [dbo].[UpdateEmailAddress] (
		@emailAddress			VARCHAR(100) = NULL
		,@personId				AS INT 
		,@emailAddressTypeId	AS INT 
		,@doNotUpdate			AS BIT
		,@doNotUpdate1			AS BIT
)
AS

BEGIN

	SET NOCOUNT ON
	
	IF EXISTS ( SELECT 1 
				FROM AdmEmailAddress
			WHERE  AdmPersonId = @personId
			AND  AdmEmailAddressTypeId = @emailAddressTypeId)
		BEGIN
			IF ( @emailAddress IS NOT NULL )
				BEGIN				
					UPDATE AdmEmailAddress
						SET EmailAddress = @emailAddress,
						DoNotUpdateEmail = @doNotUpdate
					WHERE  AdmPersonId = @personId
					AND  AdmEmailAddressTypeId = @emailAddressTypeId
				END
		END
	ELSE
	BEGIN
		INSERT INTO AdmEmailAddress	(
				EmailAddress
				,AdmPersonId
				,AdmEmailAddressTypeId
				,DoNotUpdateEmail)
			VALUES(
				@emailAddress
				,@personId
				,@emailAddressTypeId
				,@doNotUpdate)
	END

	-- Check errors
	IF @@ERROR <> 0 
	BEGIN
		RAISERROR ('Failed to update email address. Error = %s.', 16, 1, @@ERROR)
	END
		
	SET NOCOUNT OFF
END



GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Altering [dbo].[GetUserIds]'
GO
/******************************************************************          
* Name:   [GetUserIds]          
* Purpose:  Retrieves matching user details filtered by admPersonIds.           
* Note: This stored procedure is a copy of the GetUsers excpet it returns only the admPersonIds(as the design caches only Ids).
* PARAMETERS(IN)          
* Name          Description               
* -------------      -------------------------------------------          
* @username       User Name to be matched       
* @lastName    last namme to be matched    
* @firstName      first name to be matched    
* @sortColumn     Represents the sort column     
* @sortOrder   Represents the sort order to be performed on the sort column  
*********************************************************************/       
      
ALTER Procedure [dbo].[GetUserIds](      
 @username VARCHAR(36) = NULL,      
 @lastName VARCHAR(64) = NULL,      
 @firstName VARCHAR(64) = NULL,    
 @sortColumn  varchar(200)='LastName',   
 @sortOrder bit=1-->Ascending 0-->Descending  
 )  
AS BEGIN  
       
SET NOCOUNT ON            
            
  if(@firstName is null)            
   Set @firstName='%'            
  else            
   Set @firstName=@firstName+'%'             
              
  if(@lastName is null)            
   Set @lastName='%'            
  else            
   Set @lastName=@lastName+'%'             
              
  if(@userName is null)            
   Set @userName='%'            
  else            
   Set @userName=@userName+'%'    
     
  SELECT adp.Id AS [Id]  
    FROM AdmPerson adp      
    inner join FwkDomainUser fdu      
     ON adp.FwkDomainUserId = fdu.Id      
    Left Outer Join AdmInternalPerson aip      
     ON adp.Id = aip.AdmPersonId       
    Left Outer JOIN FwkDomainOrganization org      
     ON org.Id = aip.PrimaryOrganizationId   
    WHERE             
            ISNULL(adp.[firstName], '*') like @firstName            
            AND            
            ISNULL(adp.[lastName], '*') like @lastName            
            AND            
            ISNULL(fdu.[userName], '*') like @userName   
           
          ORDER BY      
            CASE @sortOrder    
              WHEN 0 THEN     
               CASE @sortColumn    
                WHEN 'LastName' THEN adp.[LastName]   
				WHEN 'FirstName' THEN adp.[FirstName]   
				WHEN 'UserName' THEN fdu.[UserName]  
				WHEN 'Institution' THEN org.[FullyQualifiedName]                                            
                ELSE adp.[LastName]   
                END    
            END                 
            DESC,    
            CASE @sortOrder    
              WHEN 1 THEN     
               CASE @sortColumn    
                WHEN 'LastName' THEN adp.[LastName]   
				WHEN 'FirstName' THEN adp.[FirstName]   
				WHEN 'UserName' THEN fdu.[UserName]  
				WHEN 'Institution' THEN org.[FullyQualifiedName]                                            
                ELSE adp.[LastName]                      
               END    
            END             
      
END      
  
  

GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Altering [dbo].[GetAgreementSearchData]'
GO


/*
Get the data used in populating the Status, AgreementType, ActivityType, and Location drop down lists on the
AgreementSearch control.
*/
ALTER  procedure [dbo].[GetAgreementSearchData](@domainUserID int)
as
begin
set nocount on

	-- Generate a list of AgreementIDs by applying the security for the specified user. This list will
	-- be used to generate other resultsets (enumerated in the comment above).
	
	create table #agreementIDs(AgreementID int, AccessLevel int)
	insert into #agreementIDs
		exec GetAgreementIDs @domainUserID
	create index Index1 on #agreementIDs (AgreementId)

	-- Generate one resultset per drop down list.
	--agreement status type
	select distinct 
		st.[Name] as StatusType,
		st.[Id] as StatusTypeID
	from AgrAgreementStatusType st
	where st.[Id] in
		(select distinct MappedToStatus
		 from AgrAgreement_Fct agf
			inner join #agreementIDs ai on ai.AgreementID = agf.AgreementID
			inner join AgrAgreementStatusType st on st.[ID] = agf.StatusTypeId)
	order by
		st.[Name]

	--agreement type
	select distinct
		aty.[Name] as AgreementType,
		aty.[Id] as AgreementTypeID
	from AgrAgreement_Fct agf
			inner join #agreementIDs ai on ai.AgreementID = agf.AgreementID
			inner join AgrAgreementType aty on aty.[ID] = agf.AgrAgreementTypeId
	order by
		aty.[Name]

	--PeopleSoft Activity type
	select distinct
		agf.PSActivityDescription as ActivityType,
		agf.PSActivityCode as ActivityCode
	from 
		AgrAgreement_Fct agf 
		inner join #agreementIDs ai on ai.AgreementID = agf.AgreementID
	where agf.ActivityTypeId IS NOT NULL and PSActivityDescription IS NOT NULL
	order by
		agf.PSActivityDescription


	--location
	select distinct
			f.[Name] as Location,
			f.[Id] as LocationID
	from AgrAgreement_Fct agf
			inner join #agreementIDs ai on ai.AgreementID = agf.AgreementID
			inner join AdmFacility f on f.[ID] = agf.FacilityId
	order by
			f.[Name]

	--sponsor type
	select distinct
		st.[Name] as SponsorType,
		st.[Id] as SponsorTypeID
	from AgrAgreement_Fct agf
			inner join AdmSponsorType st on st.[ID] = agf.SponsorTypeId
			inner join #agreementIDs ai on ai.AgreementID = agf.AgreementID
	order by
		st.[Name]

	--fund status type
	select distinct
		st.[Description] as StatusType,
		st.[Id] as StatusTypeID
	from AgrAgreement_Fct agf
			inner join #agreementIDs ai on ai.AgreementID = agf.AgreementID
			inner join AgrFundStatusType st on st.Id = agf.FundStatusTypeId
	order by
		st.[Description]

	drop table #agreementIDs

end







GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Altering [dbo].[UpdateTelephoneNumber]'
GO
SET QUOTED_IDENTIFIER OFF
GO
/******************************************************************
* VSS File Path: $Archive: /PHSRAG/Applications/WebApplications/Insight_2.2.0/Database/MissingStoredProcs/SPsMissingFrom220VSS.sql $
* Name:  UpdateTelephoneNumber
* Purpose:  
* Updates telephone number information.
*
* PARAMETERS
* Name    				Description					
* -------------  		---------------------------------------
* @telephoneNumberId	The telephone number id. (PK)
* @areaCode 			The telephone number's area code portion.
* @number 				The telephone number's number portion.
*
* RESULT SET
* Name    			Description					
* --------------	-------------------------------------------
* N/A				n/a
*
*
* RETURN VALUE
* Value    			Description					
* --------------	-------------------------------------------
* N/A				N/A
*
******************************************************************/
ALTER Procedure [dbo].[UpdateTelephoneNumber] (
		@areaCode 				VARCHAR(5) = NULL
		,@number 				VARCHAR(20) = NULL
		,@personId				AS INT 
		,@telephoneTypeId		AS INT 
		,@doNotUpdate			AS BIT
)
AS
BEGIN

	SET NOCOUNT ON

	IF EXISTS ( SELECT 1 
				FROM AdmTelephoneNumber
			WHERE  AdmPersonId = @personId
			AND  AdmTelephoneTypeId = @telephoneTypeId)
		BEGIN
			IF ( @areaCode IS NULL AND @number IS NULL)
				BEGIN
					DELETE AdmTelephoneNumber
					WHERE  AdmPersonId = @personId
					AND  AdmTelephoneTypeId = @telephoneTypeId
				END
			ELSE
				BEGIN				
					UPDATE AdmTelephoneNumber
						SET AreaCode = @areaCode
						,Number = @number
						,DoNotUpdatePhone = @doNotUpdate
					WHERE  AdmPersonId = @personId
					AND  AdmTelephoneTypeId = @telephoneTypeId
				END
		END
	ELSE
	BEGIN
		INSERT INTO AdmTelephoneNumber	(
				CountryCode
				,AreaCode
				,Number
				,AdmPersonId
				,AdmTelephoneTypeId
				,DoNotUpdatePhone )
			VALUES(
				0
				,@areaCode
				,@number
				,@personId
				,@telephoneTypeId
				,@doNotUpdate)
	END

	-- Check errors
	IF @@ERROR <> 0 
	BEGIN
		RAISERROR ('Failed to update telephone number. Error = %s.', 16, 1, @@ERROR)
	END
		
	SET NOCOUNT OFF
END


GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Creating [dbo].[spFdsANCleanupAgreeSubContractor]'
GO
SET QUOTED_IDENTIFIER ON
GO

/***************************************************************************
* Name:			spFdsANCleanupAgreeSubContractor
* Purpose:		Delete all budget records from all related tables for
*				one AgrAgreement_SubContractor_Map.Id that has been
*				deleted from the current top document
*
*				If the entire top document has been superseded or
*				deleted altogether, the cleanup process that deals
*				with that will take care of the subcontractor as well
*
* PARAMETERS
* Name						Description					
* -------------				-----------------------------------------------------------
* @AgrSubcontractorMapId
*
* ERRORS USED				Description
* -------------				-----------------------------------------------------
* n/a
*
* RETURN VALUE
* Value    					Description					
* --------------			------------------------------------------------------
* @_exitStatus				An exit status of either true or false
***************************************************************************/
CREATE PROCEDURE dbo.spFdsANCleanupAgreeSubContractor
(
	@AgrSubcontractorMapId	int
)
AS
BEGIN

	SET NOCOUNT ON

	DECLARE	@_errorValue		int
	DECLARE	@_bgtContainerId	int

	BEGIN TRANSACTION spFdsANCleanupAgreeSubContractor

	-- get the budget container Id for this subcontractor
	SELECT		@_bgtContainerId	= AgrBudgetContainerId
	FROM		AgrAgreement_SubContractor_Map
	WHERE		Id = @AgrSubcontractorMapId

	-- get AgrBudgetContainerViewId's
	SELECT		Id AS AgrBudgetContainerViewId
	INTO		#_tmpBudgetContainerViewIDs_to_Delete
	FROM		AgrBudgetContainerView
	WHERE		AgrBudgetContainerId = @_bgtContainerId

	-- now get all the related AgrBudgetId's
	SELECT		Id AS AgrBudgetId
	INTO		#_tmpBudgetIDs_to_Delete
	FROM		AgrBudget
	INNER JOIN	#_tmpBudgetContainerViewIDs_to_Delete
		ON			AgrBudget.AgrBudgetContainerViewId = #_tmpBudgetContainerViewIDs_to_Delete.AgrBudgetContainerViewId

	-- delete budget line items
	DELETE		AgrBudgetItem
	FROM		AgrBudgetItem
	INNER JOIN	#_tmpBudgetIDs_to_Delete
		ON			AgrBudgetItem.AgrBudgetId = #_tmpBudgetIDs_to_Delete.AgrBudgetId

	-- delete budget IC rates
	DELETE		AgrBudgetICRate
	FROM		AgrBudgetICRate
	INNER JOIN	#_tmpBudgetIDs_to_Delete
		ON			AgrBudgetICRate.AgrBudgetId = #_tmpBudgetIDs_to_Delete.AgrBudgetId

	-- delete the budgets
	DELETE		AgrBudget
	FROM		AgrBudget
	INNER JOIN	#_tmpBudgetIDs_to_Delete
		ON			AgrBudget.Id = #_tmpBudgetIDs_to_Delete.AgrBudgetId

	-- delete the budget container views
	DELETE		AgrBudgetContainerView
	FROM		AgrBudgetContainerView
	INNER JOIN	#_tmpBudgetContainerViewIDs_to_Delete
		ON			AgrBudgetContainerView.Id = #_tmpBudgetContainerViewIDs_to_Delete.AgrBudgetContainerViewId

	DROP TABLE	#_tmpBudgetIDs_to_Delete
	DROP TABLE	#_tmpBudgetContainerViewIDs_to_Delete

	-- delete subcontractor
	DELETE		AgrAgreement_SubContractor_Map
	WHERE		Id = @AgrSubcontractorMapId

	-- delete budget container of this subcontractor
	DELETE		AgrBudgetContainer
	WHERE		Id = @_bgtContainerId

	COMMIT TRANSACTION spFdsANCleanupAgreeSubContractor

	SET NOCOUNT OFF

END


GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Creating [dbo].[PerFeedPreProcessStaging]'
GO
SET QUOTED_IDENTIFIER OFF
GO



/******************************************************************************
**		VSS File: $/PerFeedPreProcessStaging.sql 
**		Name: PerFeedPreProcessStaging	
**		Desc: 	This procedure creates a record in the 
**				AdmSponsor table
**			
**		Return values: None
** 
**		Called by:   
**			
*******************************************************************************
**		Change History
*******************************************************************************
**		Date:		Author:				Description:
**		--------	--------			-------------------------------------------
**	
*******************************************************************************/
CREATE PROCEDURE [dbo].[PerFeedPreProcessStaging]
AS
BEGIN
	DECLARE @_errStat		INTEGER
	DECLARE @_errMsg		VARCHAR(255)
	DECLARE @_errText		VARCHAR(255)
	DECLARE @dtFeed			DATETIME

	--Step statuses
	DECLARE @STARTED		INTEGER
	DECLARE @COMPLETED		INTEGER
	DECLARE @FAILED			INTEGER
	
	--Feed Steps
	DECLARE @FILETRANSFER	INTEGER
	DECLARE @STAGING		INTEGER
	DECLARE @INITIALIZATION	INTEGER
	DECLARE @VALIDATION		INTEGER
	DECLARE @INJECTION		INTEGER
	DECLARE @CLEANUP		INTEGER

	--Set CONSTANTS 
	
	--Step statuses
	SET @STARTED		= 1
	SET @COMPLETED		= 2
	SET @FAILED			= 3
	
	--Feed Steps
	SET @FILETRANSFER	= 1
	SET @STAGING		= 2
	SET @VALIDATION		= 3
	SET @INJECTION		= 4
	SET @CLEANUP		= 5

	DECLARE @DATA_NOT_VALID		BIT
	DECLARE @DATA_VALID			BIT
	DECLARE @MANAGED_BY_INSIGHT	BIT
	DECLARE @SALARIED			INTEGER
	DECLARE @MONTHLY			INTEGER
	DECLARE @IBRIDGE			VARCHAR(10)

	SET @SALARIED			= 2
	SET @MONTHLY			= 3
	SET @MANAGED_BY_INSIGHT	= 1
	SET @DATA_NOT_VALID		= 0
	SET @DATA_VALID			= 1
	SET @IBRIDGE			= 'iBridge'

	SET NOCOUNT ON
	
	/*
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	> Get Feed date for this feed ID.
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	*/
	SELECT
		@dtFeed = getdate()

	/*
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	C r e a t e  T e m p  T a b l e  o f  F u l l  E m p l o y e e  S t a c k
	Here we select the maximum effective sequence numbers for
	a given employee, job, and effective date. The temp table is where the data
	will be manipulated.
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	*/
	select s.*
	into #TempEmployee
	from Stg_PerNewEmployee s
	where 
		s.EffectiveSeqNum = (select Max(s2.EffectiveSeqNum) from Stg_PerNewEmployee s2
							where
								s2.employeeid = s.employeeid and
								s2.EmpRecNo = s.EmpRecNo and
								s2.EffectiveDate = s.EffectiveDate) 
	order by 
		s.employeeid,
		s.EffectiveDate,
		s.EffectiveSeqNum,
		s.EmpRecNo
	
	Create index eeId on #TempEmployee (employeeid)
	/*
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	M o v e  t h e  D i s t r i b  S t a c k  t o  T e m p  T a b l e
	Only distribs related to the headers in the temp table will be moved to the temp distrib
	table.  We will manipulate the data in the temp distrib table.
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	*/
	SELECT 
		s.*
	INTO #TempEmployeeDistrib
	FROM
		Stg_PerNewEmployeeDistribution s
	INNER JOIN
		#TempEmployee tmp
	ON
		s.EmployeeId = tmp.EmployeeId and
		s.EmpRecNo = tmp.EmpRecNo and
		s.EarnEffectiveDate = tmp.EffectiveDate and
		s.EffectiveSeqNum = tmp.EffectiveSeqNum
		
	Create index eeId on #TempEmployeeDistrib (employeeid)

	/*
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	M A R K  C H A N G E  R O W S  i n  T h e  N E W  D i s t r i b  T a b l e
	Here we mark the distrib rows that are either new funds, percentage changes,
	or the bottom of the stack.  We use these marked distribs to decide if we
	want to keep a stack entry or not.  This helps remove rows that contain
	only changes that Insight does not care about.
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	*/
	update t						
	set
		ValidDataFlag = 1 
	from 
		#TempEmployeeDistrib t
	where 
		ValidDataFlag is null and
		(NOT EXISTS(select 
						1													-- CHECK FOR NEW FUND
				from 
						#TempEmployeeDistrib t1
				where
						t.EmployeeId = t1.EmployeeId and
						t.EmpRecNo = t1.EmpRecNo and
						t1.EarnEffectiveDate = (select max(t8.EarnEffectiveDate)
												from 
													#TempEmployeeDistrib t8
												where
													t8.employeeid = t.employeeid and
													t8.EmpRecNo = t.EmpRecNo and
													t8.EarnEffectiveDate < t.EarnEffectiveDate 													
									) and
						t1.EffectiveSeqNum = (   select Max(t2.EffectiveSeqNum) 
												from 
													#TempEmployeeDistrib t2
												where
													t2.employeeid = t.employeeid and
													t2.EmpRecNo = t.EmpRecNo and
													t2.EarnEffectiveDate = t1.EarnEffectiveDate) and				
						t.PayCompany = t1.PayCompany and
						t.AccountNumber = t1.AccountNumber and
						t.EarnFundNumber = t1.EarnFundNumber and
						t.EarnBusinessUnit = t1.EarnBusinessUnit) OR
			EXISTS(select 
						1													-- CHECK FOR PERCENTAGE CHANGE
				from 
						#TempEmployeeDistrib t3
				where
						t.EmployeeId = t3.EmployeeId and
						t.EmpRecNo = t3.EmpRecNo and
						t3.EarnEffectiveDate = (select max(t7.EarnEffectiveDate)
												from 
													#TempEmployeeDistrib t7
												where
													t7.employeeid = t.employeeid and
													t7.EmpRecNo = t.EmpRecNo and
													t7.EarnEffectiveDate < t.EarnEffectiveDate												
												) and
						t3.EffectiveSeqNum = (   select Max(t6.EffectiveSeqNum) 
												from 
													#TempEmployeeDistrib t6
												where
													t6.employeeid = t.employeeid and
													t6.EmpRecNo = t.EmpRecNo and
													t6.EarnEffectiveDate = t3.EarnEffectiveDate) and				
						t.PayCompany = t3.PayCompany and
						t.AccountNumber = t3.AccountNumber and
						t.EarnFundNumber = t3.EarnFundNumber and
						ABS(t.EarnPercent - t3.EarnPercent) >= .01 and
						t.EarnBusinessUnit = t3.EarnBusinessUnit) OR
		NOT EXISTS(select 
						1													-- CHECK FOR BOTTOM OF STACK
				from 
						#TempEmployeeDistrib t4
				where
						t.EmployeeId = t4.EmployeeId and
						t.EmpRecNo = t4.EmpRecNo and
						t4.EarnEffectiveDate = (select max(t9.EarnEffectiveDate)
												from 
													#TempEmployeeDistrib t9
												where
													t9.employeeid = t.employeeid and
													t9.EmpRecNo = t.EmpRecNo and
													t9.EarnEffectiveDate < t.EarnEffectiveDate												
									) and
						t4.EffectiveSeqNum = (   select Max(t5.EffectiveSeqNum) 
												from 
													#TempEmployeeDistrib t5
												where
													t5.employeeid = t.employeeid and
													t5.EmpRecNo = t.EmpRecNo and
													t5.EarnEffectiveDate = t4.EarnEffectiveDate)
					) OR	
		NOT EXISTS(select 
						1													-- CHECK FOR TOP OF STACK
				from 
						#TempEmployeeDistrib t12
				where
						t.EmployeeId = t12.EmployeeId and
						t.EmpRecNo = t12.EmpRecNo and
						t12.EarnEffectiveDate = (select min(t13.EarnEffectiveDate)
												from 
													#TempEmployeeDistrib t13
												where
													t13.employeeid = t.employeeid and
													t13.EmpRecNo = t.EmpRecNo and
													t13.EarnEffectiveDate > t.EarnEffectiveDate												
									) and
						t12.EffectiveSeqNum = (   select Max(t14.EffectiveSeqNum) 
												from 
													#TempEmployeeDistrib t14
												where
													t14.employeeid = t.employeeid and
													t14.EmpRecNo = t.EmpRecNo and
													t14.EarnEffectiveDate = t12.EarnEffectiveDate)
					) OR	
			EXISTS(	select 
						1												-- CHECK FOR SALARY CHANGE.
					from
						#TempEmployee t10
					inner join
						#TempEmployee t11
					on
						t11.employeeid = t10.employeeid and
						t11.EmpRecNo = t10.EmpRecNo and
						t11.EffectiveDate = (Select max(t12.EffectiveDate)
												from
													#TempEmployee t12
												where
													t12.employeeid = t11.employeeid and
													t12.EmpRecNo = t11.EmpRecNo and
													t12.EffectiveDate < t.EarnEffectiveDate) 
					where
						t.employeeid = t10.employeeid and
						t.EmpRecNo = t10.EmpRecNo and
						t.EarnEffectiveDate = t10.EffectiveDate and
						(ROUND(t10.AnnualSalary,2) <> ROUND(t11.AnnualSalary,2) or
						ROUND(t10.StandardHours,2) <> ROUND(t11.StandardHours,2) or
						t10.HourlyRate <> t11.HourlyRate 
					)) 
		)
	/*			
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	D e l e t e  N O  C H A N G E  R O W S  f r o m  t h e  T e m p  T a b l e
	Here we delete from the stack any row that represents a change that does
	not effect the data we use (Salary or distrib).  This removes unnecessary noise.
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	*/
	Delete t
	from 
		#TempEmployee t
	where 
		exists(	select 
					t1.effectivedate 
				from 
					#TempEmployee t1
				where
					t1.employeeid = t.employeeid and
					t1.EmpRecNo = t.EmpRecNo and
					t1.effectivedate = (select 
											max(t2.effectivedate)
										from
											#TempEmployee t2
										where
											t2.effectivedate < t.effectivedate and
											t2.employeeid = t.employeeid and
											t2.EmpRecNo = t.EmpRecNo 
										) and
					ROUND(t1.AnnualSalary,2) = ROUND(t.AnnualSalary,2) and
					t1.HourlyRate = t.HourlyRate and
					ROUND(t1.StandardHours,2) = ROUND(t.StandardHours,2) 
					) 
		AND
		NOT EXISTS(	SELECT top 1
						sd1.Id
					FROM
						#TempEmployeeDistrib sd1
					WHERE
						t.employeeid = sd1.employeeid and
						t.EmpRecNo = sd1.EmpRecNo and
						t.EffectiveDate = sd1.EarnEffectiveDate and
						sd1.ValidDataFlag = 1)				

	/*			
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	D e l e t e  N O  C H A N G E  R O W S  i n  t h e  T e m p  D i s t r i b
	Here we delete from the stack any row that represents a change that does
	not effect the data we use (Distrib changes).  This removes unnecessary noise.
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	*/
	Delete t
	from 
		#TempEmployeeDistrib t
	where
		NOT EXISTS(	SELECT top 1
						sd1.Id
					FROM
						#TempEmployeeDistrib sd1
					WHERE
						t.employeeid = sd1.employeeid and
						t.EmpRecNo = sd1.EmpRecNo and
						t.EarnEffectiveDate = sd1.EarnEffectiveDate and
						sd1.ValidDataFlag = 1)
	
	/*
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	M o v e  t h e  E d i t e d  D i s t r i b  S t a c k  t o  t h e  F i n a l  S t a g i n g
	Now that we have the data in a format we are setup to process, we can move it
	to the final staging table for processing.  
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	*/
	INSERT INTO Stg_PerEmployeeDistribution
	(
		AccountNumber
		,BusinessUnit
		,EarnBusinessUnit
		,EarnEffectiveDate
		,EarnFundNumber
		,EarnPercent
		,EffectiveSeqNum
		,EmployeeID
		,EmpRecNo
		,FundNumber
		,HRDepartmentIdentifier
		,JobCode
		,PayCompany
		,PercentEffort
	)
	SELECT 
		t.AccountNumber
		,t.BusinessUnit
		,t.EarnBusinessUnit
		,t.EarnEffectiveDate
		,t.EarnFundNumber
		,t.EarnPercent
		,t.EffectiveSeqNum
		,t.EmployeeID
		,t.EmpRecNo
		,t.FundNumber
		,t.HRDepartmentIdentifier
		,t.JobCode
		,t.PayCompany
		,t.PercentEffort
	FROM
		#TempEmployeeDistrib t
	INNER JOIN
		#TempEmployee tmp
	ON
		t.EmployeeId = tmp.EmployeeId and
		t.EmpRecNo = tmp.EmpRecNo and
		t.EarnEffectiveDate = tmp.EffectiveDate and
		t.EffectiveSeqNum = tmp.EffectiveSeqNum

	/*			
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	D e l e t e  N O  C H A N G E  R O W S  f r o m  t h e  T e m p  T a b l e
	Here we delete from the stack any row that represents a change that does
	not effect the data we use (Salary changes).  This removes unnecessary noise.
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	*/
	Delete t
	from 
		#TempEmployee t
	where 
		exists(	select 
					t1.effectivedate 
				from 
					#TempEmployee t1
				where
					t1.employeeid = t.employeeid and
					t1.EmpRecNo = t.EmpRecNo and
					t1.effectivedate = (select 
											max(t2.effectivedate)
										from
											#TempEmployee t2
										where
											t2.effectivedate < t.effectivedate and
											t2.employeeid = t.employeeid and
											t2.EmpRecNo = t.EmpRecNo 
										) and
					ROUND(t1.AnnualSalary,2) = ROUND(t.AnnualSalary,2) and
					t1.HourlyRate = t.HourlyRate and
					ROUND(t1.StandardHours,2) = ROUND(t.StandardHours,2) 
					) 
	/*			
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	U p d a t e  LATEST HR DEPT, JOB CODE, EMPLOYEE STATUS in T e m p  T a b l e
	Since we only save the earliest employee job data with the same salary and no
	distribution changes
	(Because we want the earliest effective date without a salary or distribution
	change),
	Therefore, we need to update it with the most recent job code, hrdepartment
	and employee status because these are significant.
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	*/
	Update t
	Set
		HRDepartmentIdentifier	= sne.HRDepartmentIdentifier,
		JobCode					= sne.JobCode,
		EmployeeStatus			= sne.EmployeeStatus,
		BusinessUnit			= sne.BusinessUnit,
		FirstName				= sne.FirstName,
		HRDepartmentName		= sne.HRDepartmentName,
		JobTitle				= sne.JobTitle,
		LastIncreaseDate		= sne.LastIncreaseDate,
		LastName				= sne.LastName,
		MiddleName				= sne.MiddleName,
		PayCompany				= sne.PayCompany,
		PayFrequency			= sne.PayFrequency,
		PayType					= sne.PayType
	from 
		#TempEmployee t
	inner join
		Stg_PerNewEmployee sne	
	on
		sne.employeeid = t.employeeid and
		sne.EmpRecNo = t.EmpRecNo and		
		sne.effectivedate = (select 
								max(sne1.effectivedate) 
							from 
								Stg_PerNewEmployee sne1
							where
								sne1.employeeid = sne.employeeid and
								sne1.EmpRecNo = sne.EmpRecNo) and 			
		sne.EffectiveSeqNum = (select max(sne2.EffectiveSeqNum)
								from
									Stg_PerNewEmployee sne2
								Where
									sne2.EmployeeId = sne.EmployeeId
									and sne2.EmpRecNo = sne.EmpRecNo
									and sne2.EffectiveDate = sne.EffectiveDate)

	
	/*
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	M o v e  t h e  E d i t e d  H e a d e r  S t a c k  t o  t h e  F i n a l  S t a g i n g
	Now that we have the data in a format we are setup to process, we can move it
	to the final staging table for processing.  
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	*/
	INSERT INTO Stg_PerEmployee
	(
		ActionDate
		,AnnualSalary
		,BusinessUnit
		,EffectiveDate
		,EffectiveSeqNum
		,EmployeeID
		,EmpRecNo
		,EmployeeStatus
		,FirstName
		,HourlyRate
		,HRDepartmentIdentifier
		,HRDepartmentName
		,JobCode
		,JobTitle
		,LastIncreaseDate
		,LastName
		,MiddleName
		,PayCompany
		,PayFrequency
		,PayType
		,StandardHours
	)
	SELECT 
		t.ActionDate
		,t.AnnualSalary
		,t.BusinessUnit
		,t.EffectiveDate
		,t.EffectiveSeqNum
		,t.EmployeeID
		,t.EmpRecNo
		,t.EmployeeStatus
		,t.FirstName
		,t.HourlyRate
		,t.HRDepartmentIdentifier
		,t.HRDepartmentName
		,t.JobCode
		,t.JobTitle
		,t.LastIncreaseDate
		,t.LastName
		,t.MiddleName
		,t.PayCompany
		,t.PayFrequency
		,t.PayType
		,t.StandardHours
	FROM
		#TempEmployee t

	drop table #TempEmployee
	drop table #TempEmployeeDistrib

	SET NOCOUNT OFF
	RETURN

ErrorHandler:
	BEGIN
		IF @_errStat <> 0
		BEGIN
			SELECT @_errText = description
			FROM master..SYSMESSAGES
			WHERE error = @_errStat
			RAISERROR ('Error occurred while %s.  The error was %d message was: (%s)',
			16, 1,@_errMsg,@_errStat,@_errText) With LOG
			RETURN @_errStat
		END
	END

END




GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Altering [dbo].[UpdateUserAccessToClinicalTrialBudget]'
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE dbo.UpdateUserAccessToClinicalTrialBudget (
		@domainUserId			INTEGER,
		@budgetId				INTEGER,
		@readPending			INTEGER,
		@readFinal				INTEGER,
		@modifyPending			INTEGER
)
AS
BEGIN

SET NOCOUNT ON

DECLARE @roleBitmask int
DECLARE @pendingBudgetReadAccessBit INT
DECLARE @finalBudgetReadAccessBit INT
DECLARE @pendingBudgetModifyAccessBit INT
DECLARE @resourceId int
DECLARE @budgetResourceTypeId int
DECLARE @str varchar(4000)

SET @pendingBudgetReadAccessBit = 8192
SET @finalBudgetReadAccessBit = 4096
SET @pendingBudgetModifyAccessBit = 32768
SET @budgetResourceTypeId = 3

SELECT @resourceId = FwkResourceId 
FROM ClinicalTrialBudget 
WHERE Id = @budgetId

DECLARE @piId INT
DECLARE @originatorId INT

SELECT @piId = PIPersonId FROM ClinicalTrialBudget WHERE Id = @budgetId
SELECT @originatorId = OriginatorPersonId FROM ClinicalTrialBudget WHERE Id = @budgetId

IF ((@piID != @domainUserId) and (@originatorId != @domainUserId))
	BEGIN		
		SELECT @roleBitmask = frdum.AccessRightBitmask							
							from FwkResource_DomainUser_Map frdum
							inner join FwkResource fr
							on fr.Id = Frdum.FwkResourceId
							inner join ClinicalTrialBudget ctb
							on ctb.FwkResourceId = frdum.FwkResourceId
							where frdum.FwkDomainUserId = @domainUserId 
							and frdum.FwkResourceId=@resourceId 
							and fr.FwkResourceTypeId=@budgetResourceTypeId
							and ctb.Id = @budgetId						

		if (@roleBitmask is null) set @roleBitmask = 0

		if ((@modifyPending = 1) and (@readPending =0)) set @readPending = 1
		
		IF (((@roleBitmask & @pendingBudgetReadAccessBit) != @pendingBudgetReadAccessBit) and @readPending = 1)
		BEGIN		
			set @roleBitmask = @roleBitmask + @pendingBudgetReadAccessBit		
		END
		ELSE IF (((@roleBitmask & @pendingBudgetReadAccessBit) = @pendingBudgetReadAccessBit) and @readPending = 0)
		BEGIN
			set @roleBitmask = @roleBitmask - @pendingBudgetReadAccessBit
		END
		IF (((@roleBitmask & @finalBudgetReadAccessBit) != @finalBudgetReadAccessBit) and @readFinal = 1)
		BEGIN
			set @roleBitmask = @roleBitmask + @finalBudgetReadAccessBit
		END
		ELSE IF (((@roleBitmask & @finalBudgetReadAccessBit) = @finalBudgetReadAccessBit) and @readFinal = 0)
		BEGIN
			set @roleBitmask = @roleBitmask - @finalBudgetReadAccessBit
		END
		IF (((@roleBitmask & @pendingBudgetModifyAccessBit) != @pendingBudgetModifyAccessBit) and @modifyPending = 1)
		BEGIN
			set @roleBitmask = @roleBitmask + @pendingBudgetModifyAccessBit
		END
		ELSE IF (((@roleBitmask & @pendingBudgetModifyAccessBit) = @pendingBudgetModifyAccessBit) and @modifyPending = 0)
		BEGIN
			set @roleBitmask = @roleBitmask - @pendingBudgetModifyAccessBit
		END				

		exec ChangeDirectResourceAccess @domainUserId,@resourceId,@roleBitmask		
	END		
END
GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Altering [dbo].[GetMergeCandidates]'
GO

/*
The spoc gets a list of potentially 'duplicated' users. It does the matching by last names and the first three characters of 
the first name.

Note:
-----------
The fact that users match by the criteria explained above does not necessarily mean they are duplicates.
The person using the Merge tool should look further into the data and make necessary determination.
*/

ALTER Procedure [dbo].[GetMergeCandidates] (
	@lastName VARCHAR(64)
) AS
BEGIN

	set nocount on
	
	declare @agrResourceTypeId int
	declare @humanResourceTypeId int
	declare @ctResourceTypeId int
	
	set @agrResourceTypeId = 1
	set @humanResourceTypeId = 2
	set @ctResourceTypeId = 3
	
	set @lastName = rtrim(ltrim(@lastName))
	
	create table #mergeCandidates(LastName varchar(64), FirstName varchar(64))
	
	insert into #mergeCandidates (LastName, FirstName)
	select LastName, FirstName from AdmPerson where LastName = @lastName

	select distinct		
				ap.Id as PersonId,
				'' as MergeToId,
				case when ap.AdmPersonTypeId = 1 then 'Internal' else 'External' end as PersonType, 
				case when fdu.Username is null then '' else fdu.Username end as Username,
				ap.LastName,
				ap.FirstName,
				case when ap.MiddleName is null then '' else ap.MiddleName end as MiddleName,
				(select count(*)  from UserResourceCache where ResourceTypeId = @agrResourceTypeId and FwkDomainUserId = fdu.Id) as Agreements,
				(select count(*) from UserResourceCache where ResourceTypeId = @humanResourceTypeId  and FwkDomainUserId = fdu.Id) as Humans,
				(select count(*) from UserResourceCache where ResourceTypeId = @ctResourceTypeId and FwkDomainUserId = fdu.Id) as ClinicalTrials,
				case when aip.EmployeeNumber is null then '' else aip.EmployeeNumber end as EmployeeNumber,
				case when org.FullyQualifiedName is null then '' else org.FullyQualifiedName end as Organization,
				case  when fau.Id is null then 'False'
					when (fau.IsActiveBitMask & 4) = 0 then 'False'
					else 'True' end as Registered,	
				case when dp.IsActive = 1 then 'Active' else 'Inactive' end as DomainStatus,
				'' as Comment
	from		AdmPerson ap
	left join	FwkDomainUser fdu
	on			fdu.Id = ap.FwkDomainUserId
	left join   AdmPerson_FwkDomainOrganization_Map orgMap on orgMap.AdmPersonId = ap.Id
	left join	FwkDomainOrganization org on org.Id = orgMap.FwkDomainOrganizationId
	left join	FwkApplicationUser fau on fau.FwkDomainUserId = fdu.Id
	left join	FwkDomainPrincipal dp
		on		fdu.FwkPrincipalId = dp.Id
	left join	AdmInternalPerson aip on aip.AdmPersonId = ap.Id
	where		ap.LastName = @lastName
				and ( -- makes sure there are 'duplicates', matches by first three characters of the first name
						(select count(*) from #mergeCandidates mc1 where substring(ap.FirstName, 1, 3) = substring(mc1.FirstName, 1, 3)) > 1
					) 
	order by	ap.LastName, ap.FirstName
	
	drop table #mergeCandidates
	
END

GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Altering [dbo].[UpdateEmailsFromRex]'
GO
SET QUOTED_IDENTIFIER OFF
GO
/******************************************************************
* VSS File Path: $Archive: /PHSRAG/Applications/WebApplications/Insight_2.2.0/Database/MissingStoredProcs/SPsMissingFrom220VSS.sql $
* Name:  UpdateEmailsFromRex
* Purpose:  
* Updates email information in Insight from Rex values, excluding
*	any records that have been manually updated in Insight.
*
* PARAMETERS
* Name    			Description					
* -------------  	---------------------------------------
* N/A				N/A
*
* RESULT SET
* Name    			Description					
* --------------	-------------------------------------------
* N/A				n/a
*
*
* RETURN VALUE
* Value    			Description					
* --------------	-------------------------------------------
* N/A				N/A
*
******************************************************************/
ALTER Procedure [dbo].[UpdateEmailsFromRex] 
AS

BEGIN

	SET NOCOUNT ON


	BEGIN
		-- First, any emails that are different, but blank in Insigh, update the blank ones to be the value from Rex.
		Update AdmEmailAddress set EmailAddress = S.StagingEmail FROM (
		select S.EmailAddress as StagingEmail, E.EmailAddress as InsightEmail, E.Id as AdmEmailAddressId
		from Stg_RexEmails S
		inner join AdmPerson A on A.Id = S.ADmPersonId
		inner join AdmEmailAddress e On E.AdmPersonId = A.Id
		where AdmEmailAddressTypeId = 1 AND
			DoNotUpdateEmail = 0 AND
			UPPER(S.EmailAddress) != UPPER(E.EmailAddress)
			AND E.EmailAddress = '') S
		WHERE S.AdmEmailAddressId = AdmEmailAddress.Id AND
			(AdmEmailAddress.EmailAddress = '')
	END

	BEGIN
		-- see if any of the Rex emails are in the person's email list as non-primary. If they are, 
		-- flip the status. So first, update the non-primary flag.
		BEGIN
			UPDATE Stg_RexEmails set existsNonPrimary = 1 where EmailAddress in (
			select S.EmailAddress 
			from Stg_RexEmails S
			inner join AdmPerson A on A.Id = S.ADmPersonId
			inner join AdmEmailAddress e On E.AdmPersonId = A.Id
			where AdmEmailAddressTypeId != 1 AND
				UPPER(S.EmailAddress) != UPPER(E.EmailAddress) )
		END

		-- set them all as non-primary for the appropriate people
		BEGIN
			UPDATE AdmEmailAddress set AdmEmailAddressTypeId = 2 where AdmPersonId in (
				select E.AdmPersonId from AdmEmailAddress E
					inner join Stg_RexEmails S
						on UPPER(S.EmailAddress) = UPPER(E.EmailAddress)
				WHERE S.ExistsNonPrimary = 1)
				AND DoNotUpdateEmail  = 0
		END

		--- Now mark the ones as primary
		BEGIN
			UPDATE AdmEmailAddress set AdmEmailAddressTypeId = 1 where Id in (
				select E.Id from AdmEmailAddress E
					inner join Stg_RexEmails S
						on UPPER(S.EmailAddress) = UPPER(E.EmailAddress)
				WHERE S.ExistsNonPrimary = 1)
				AND DoNotUpdateEmail  = 0
		END
	END

	BEGIN
		-- now set the current ones to secondary and insert the remaining ones...
		UPDATE AdmEmailAddress set AdmEmailAddressTypeId = 2 where AdmPersonId in (
			select A.Id
				from Stg_RexEmails S
				inner join AdmPerson A on A.Id = S.ADmPersonId
				inner join AdmEmailAddress e On E.AdmPersonId = A.Id
				where AdmEmailAddressTypeId = 1 AND
					UPPER(S.EmailAddress) != UPPER(E.EmailAddress))
			AND DoNotUpdateEmail = 0
		
		-- set those rows to be inserted
		Update Stg_RexEmails set ToBeInserted = 1 where EmailAddress in (
			SELECT S.EmailAddress
			FROM Stg_RexEmails S
			Where UPPER(S.EmailAddress) not in (select distinct(UPPER(EmailAddress)) from AdmEmailAddress))

		-- insert	
		INSERT INTO AdmEmailAddress ( EmailAddress, AdmPersonId, AdmEmailAddressTypeId, DoNotUpdateEmail ) 
			SELECT S.EmailAddress, S.AdmPersonId, 1, 1
			FROM Stg_RexEmails S
			Where S.ToBeInserted = 1

	END

	BEGIN
		BEGIN
		-- Update those emails where there are two non-primaries but no primary (Rex allows this)
		update AdmEmailAddress set AdmEmailAddressTypeId = 1 where Id in (
			select max(Id) From AdmEmailAddress where AdmPersonId in (
				select admpersonId from AdmEmailAddress
				where AdmEmailAddressTypeId = 2	
				and AdmPersonId not in 
					(select distinct(AdmPersonId) from AdmEmailAddress where AdmEmailAddressTypeId = 1)
				group by AdmPersonId, AdmEmailAddressTypeId
				having count(AdmPersonId) > 1)
			group by admPersonId)
			AND DoNotUpdateEmail = 0
		END

		BEGIN
		-- Now update those with only one email to set that as the primary
		update AdmEmailAddress set AdmEmailAddressTypeId = 1 where Id in (
			select max(Id) From AdmEmailAddress where AdmPersonId in (
				select admpersonId from AdmEmailAddress
				where AdmEmailAddressTypeId = 2	
				and AdmPersonId not in 
					(select distinct(AdmPersonId) from AdmEmailAddress where AdmEmailAddressTypeId = 1)
				group by AdmPersonId, AdmEmailAddressTypeId
				having count(AdmPersonId) = 1)
			group by admPersonId)
		END
	END


	-- Check errors
	IF @@ERROR <> 0 
	BEGIN
		RAISERROR ('Failed to update emails from Rex. Error = %s.', 16, 1, @@ERROR)
	END
		
	SET NOCOUNT OFF
END

GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Creating [dbo].[spFdsNStartFeed]'
GO
SET QUOTED_IDENTIFIER ON
GO

/***************************************************************************
* Name:			spFdsNStartFeed
* Purpose:		Used to start an instance of a feed type
*
*
* PARAMETERS
* Name					Description					
* -------------			-----------------------------------------------------------
* @_DTSPackageName		Input
* @_FeedInstanceId		Output
* @_DateLastSuccess		Output	
*
* ERRORS USED		Description
* -------------		-----------------------------------------------------
* n/a
*
* RETURN VALUE
* Value    			Description					
* --------------	------------------------------------------------------
*	0				Succeeded
*	1				Failed
***************************************************************************/

CREATE PROCEDURE dbo.spFdsNStartFeed (
	@_DTSPackageName varchar(50)
,	@_FeedInstanceId integer output
,	@_DateLastSuccess datetime output
)
AS
BEGIN
	SET NOCOUNT ON

	DECLARE @FEED_SUCCESS	Integer
	DECLARE @FEED_INPROCESS Integer
	Set @FEED_SUCCESS = 2
	Set @FEED_INPROCESS = 1

	DECLARE @_myFeedTypeId Integer

	/*
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	Get Feed type
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	*/
	select
		@_myFeedTypeId = [Id]
	from
		SvcFeedType
	where
		[Name] = @_DTSPackageName

	/*
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	If no Feed type, stop here and return nulls!
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	*/
	if @_myFeedTypeId is null
	Begin
		Set @_FeedInstanceId = null
		Set @_DateLastSuccess = null
		return 1
	End

	/*
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	Get the date of the last successful run!
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	*/
	Set @_DateLastSuccess = COALESCE(  (Select
											S.StartDate
										From
											SvcFeedRun S
										Where
											S.SvcFeedTypeId = @_myFeedTypeId
											and S.SvcFeedStatusTypeId = @FEED_SUCCESS
											and S.StartDate =	(Select top 1
																	Max(S1.StartDate)
															 	From
																	SvcFeedRun S1
																Where
																	S1.SvcFeedTypeId = @_myFeedTypeId
																	and S1.SvcFeedStatusTypeId = @FEED_SUCCESS))
									, '1/1/1900')

	/*
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	Create a new feed instance and return the instance Id!
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	*/
	Insert into SvcFeedRun	(SvcFeedTypeId, SvcFeedStatusTypeId, StartDate, EndDate)
		Values				(@_myFeedTypeId, @FEED_INPROCESS, getdate(), null)

	Select @_FeedInstanceId = SCOPE_IDENTITY()

	SET NOCOUNT OFF

	RETURN 0

END

GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Altering [dbo].[DeleteSvcEntityStaffedPerson]'
GO

  
  
ALTER PROCEDURE [dbo].[DeleteSvcEntityStaffedPerson]   
  
AS  
BEGIN  
 SET NOCOUNT ON;  
  
 SELECT DISTINCT MAP.Id  
 INTO #tempIDs  
 FROM SvcEntity_AdmStaffedPerson_Map MAP JOIN Stg_IE_SvcEntityStaffedPerson_Ctl  
 ON MAP.SvcEntityId =  Stg_IE_SvcEntityStaffedPerson_Ctl.SvcEntityId  
 WHERE NOT EXISTS (SELECT * FROM Stg_IE_SvcEntityStaffedPerson_Ctl STG  
 WHERE STG.SvcEntityStaffedPersonMapId = MAP.Id)  
 
 DELETE AgrStaffedPersonEffortYear  
 WHERE SvcEntityStaffedPersonMapId IN (SELECT Id FROM #tempIDs)   


  
 DELETE SvcEntity_AdmStaffedPerson_Map  
 WHERE Id IN (SELECT Id FROM #tempIDs)   
  
 DELETE PEY  
 FROM AgrStaffedPersonEffortYear PEY JOIN Stg_IE_SvcEntityStaffedPerson_Ctl STG  
  ON STG.SvcEntityStaffedPersonMapId = PEY.SvcEntityStaffedPersonMapId  
 WHERE NOT EXISTS (SELECT PEY.Id FROM Stg_IE_SvcEntityStaffedPerson_Ctl STG  
 WHERE STG.SvcEntityStaffedPersonMapId = PEY.SvcEntityStaffedPersonMapId  
 AND STG.AgrBudgetViewTypeId = PEY.AgrBudgetViewTypeId  
 AND STG.nYear = PEY.SequenceYear)   
  
   
END  


GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Altering [dbo].[GetProtocolProcess]'
GO

/******************************************************************
* Name:			GetProtocolProcess
* Purpose:		Retrieves a ProtocolProcess based on the ProtocolProcess's
*					id passed in as a parameter.
*
* PARAMETERS
* Name    						Description					
* -------------  				-------------------------------------------
* @id							The Id of the ProtocolProcess to be retrieved.
******************************************************************/

ALTER Procedure [dbo].[GetProtocolProcess] (
		@id		INTEGER	
)
AS
BEGIN

	SET NOCOUNT ON

	Select			[Id],
					ProtocolId, 
					[Name], 
					Type,
					Status, 
					Locked,
					LastLockedVersion,
					ReceivedDate, 
					ApprovalDate,
					ExpirationDate,
					PrimaryReviewerId,
					SecondaryReviewerId,
					SubmitterId,
					CreateDate,
					LastModifiedDate,
					LastModifiedByUserId,
					SubmittedDate,
					ShowStaff,
					ShowAttachments,
					RexIRBStatusId,
					BeenSubmitted,
					HasBeenLocked,
					Resubmission
					
			FROM ProtocolProcess
			
			WHERE	Id = @id
	
END



GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Creating [dbo].[GetExpenseInfo2]'
GO



---------------------------
--Modifications:
--08-21-2007	Performance improvements: (nolock), removed indexes for inserts
--09-14-2007	Fix for Cartesian Join
----------------------------------------
CREATE procedure [dbo].[GetExpenseInfo2]
( 
	@SessionId varchar(100),
	@domainUserID int,
	@includeProgramProjects bit = null,
	@fundNumber varchar(8) = null,
	@folderNumber varchar(16) = null,
	@bicsNumber varchar(10) = null,
	@walkerNumber varchar(10) = null,
	@sponsorNumber varchar(32) = null,
	@sponsorName varchar(64) = null,
	@sponsorTypeID int = null,
	@agreementTypeID int = null,
	@activityCode varchar(4)= null,
	@locationID int = null,
	@budgetStartDate datetime = null,
	@budgetEndDate datetime = null,
	@projectStartDate datetime = null,
	@projectEndDate datetime = null,
	@piID int = null,
	@chiefCodeList varchar(1000) = null,
	@sponsorGroupTypeID int = null,
	@budgetEndingDays int = null,
	@projectEndingDays int = null,
	@fundCreatedDays int = null,
	@lowBalance decimal(17,2) = null,
	@highBalance decimal(17,2) = null,
	@agreementStatusTypeList varchar(50)= null,
	@fundStatusTypeID int	= null,
	@categoryID int = null,
	@accountNumber varchar(10) = null,
	@expenseDateFrom datetime = null,
	@expenseDateTo datetime = null,
	@incomingFundNumber varchar(8) = null,
	@monthEndingDate datetime = null
)
as
begin
	set nocount on

	declare @accountID int
	if isnull(@accountNumber,'') = ''
		set @accountID = 0
	else
		set @accountID = (select Id from FinAccount where Number = @accountNumber)

	set @includeProgramProjects = isnull(@includeProgramProjects, 0)
	set @fundNumber = isnull(@fundNumber, '')
	set @folderNumber = isnull(@folderNumber, '')
	set @bicsNumber = isnull(@bicsNumber, '')
	set @walkerNumber = isnull(@walkerNumber, '')
	set @sponsorNumber = isnull(@sponsorNumber, '')
	set @sponsorName = isnull(@sponsorName, '')
	set @sponsorTypeID = isnull(@sponsorTypeID, 0)
	set @agreementTypeID = isnull(@agreementTypeID, 0)
	set @activityCode = isnull(@activityCode, '')
	set @locationID = isnull(@locationID, 0)
	set @budgetStartDate = isnull(@budgetStartDate, '01/01/1900')
	set @budgetEndDate = isnull(@budgetEndDate, '01/01/1900')
	set @projectStartDate = isnull(@projectStartDate, '01/01/1900')
	set @projectEndDate = isnull(@projectEndDate, '01/01/1900')
	set @piID = isnull(@piID, 0)
	set @chiefCodeList = isnull(@chiefCodeList, '')
	set @sponsorGroupTypeID = isnull(@sponsorGroupTypeID, 0)
	set @budgetEndingDays = isnull(@budgetEndingDays, 0)
	set @projectEndingDays = isnull(@projectEndingDays, 0)
	set @fundCreatedDays = isnull(@fundCreatedDays, 0)
	set @lowBalance = isnull(@lowBalance, -922337203685477)
	set @highBalance = isnull(@highBalance, 922337203685477)
	set @agreementStatusTypeList = isnull(@agreementStatusTypeList, '')
	set @fundStatusTypeID = isnull(@fundStatusTypeID, 1)
	set @categoryID = isnull(@categoryID, 0)
	set @accountID = isnull(@accountID, 0)
	set @incomingFundNumber = isnull(@incomingFundNumber, '')
	set @monthEndingDate = isnull(@monthEndingDate, '')

	declare @directCosts int
	set @directCosts = 2

	declare @indirectCosts int
	set @indirectCosts = 3

	declare @revenue int
	set @revenue = 1

	declare @awardedBudgetTypeId int
	set @awardedBudgetTypeId = 3

	declare @viewFinancialInfoBitValue int
	set @viewFinancialInfoBitValue = 4

	declare @viewPendingAgreementsBitValue int 
	set @viewPendingAgreementsBitValue = 32

	declare @authorizedRightsBitMask int
	set @authorizedRightsBitMask = @viewFinancialInfoBitValue + @viewPendingAgreementsBitValue

	declare @t0 datetime
	set @t0 = current_timestamp

	-- Compute the fund ID based on whether or not the invocation is from an overview or detail context. In the former case,
	-- the @incomingFundNumber is not specified. In the later case, the specified fund number will only be accepted for
	-- further processing only if the specified user has access to that fund.

	declare @fundID int
	if (@incomingFundNumber = '')
		set @fundId = 0
	else
	begin
		select @fundID = [ID] from AgrFund where FundNumber = @incomingFundNumber
	end

	-- Generate a list of funds that are accessible to the specified user. When in the detail context, there would only
	-- be one fund to worry about. Since this list of accessible funds is used multiple times, the list is stored in
	-- a permanent table for the user.

	IF OBJECT_ID('tempdb..#TempFundCollection') is not null drop table #TempFundCollection
	create table #TempFundCollection (FundID int not null, AccessLevel int not null)

	If (@incomingFundNumber = '') begin
		exec GetFundCollection @SessionId, @domainUserID, @authorizedRightsBitMask
		--Create Unique Index FundId on #TempFundCollection (FundId)
	end
	else
		insert into #TempFundCollection (FundID,AccessLevel) values (@fundID,@authorizedRightsBitMask)

	declare @t1 datetime
	set @t1 = current_timestamp
	print 'Step_1: ' + cast(datediff(ss, @t0, @t1) as varchar)

	-- The expense date range should be from the first day of the 'from' month/year to the last day of the 'to' month/year.
	-- The 'to' date is clamped to the first day of the current month/year.
	-- There are three scenairos to handle:
	-- 1. Both dates are specified
	-- 2. Neither dates are specified
	-- 3. One of the dates is specified
	-- 3a. If the 'from' date is specified, the 'to' date is the mininum of the last gl close date and the 'from' + 12 months
	-- 3b. If the 'to' date is specified, the 'from' date is 'to' - 12 months

	Declare @refreshDatesTable table (glPostAsOfDate datetime,salaryAsOfDate datetime, poapAsOfDate datetime)

	Insert into @refreshDatesTable Exec GetRefreshDates

	Declare @glPostAsOfDate DateTime
	select @glPostAsOfDate = glPostAsOfDate from @refreshDatesTable

	if ((@expenseDateTo is null) or (@expenseDateTo > @glPostAsOfDate))
		set @expenseDateTo = @glPostAsOfDate

	if (@expenseDateFrom is null)
		set @expenseDateFrom = '01/01/1900'		--dateadd(day, 1, dateadd(month, -12, @expenseDateTo))
	else
		set @expenseDateFrom = dateadd(day, -datepart(day, @expenseDateFrom) + 1, @expenseDateFrom)

	-- Retrieve the list of month-end dates between the from and to date range. This is saved in a table variable
	-- for later reuse.
	create table #dateRange ([ID] int primary key identity(1, 1), MonthEndingDate datetime)

	insert into #dateRange
		select Dates from dbo.GetDateRanges(@expenseDateFrom, @expenseDateTo)

	declare @t2 datetime
	set @t2 = current_timestamp
	print 'Step_2: ' + cast(datediff(ss, @t1, @t2) as varchar)

	-- Retrive account data and stored it in a table variable for later use. We are interested in all account categories other than
	-- indirect costs, investment income, and other income.
	create table #lookUp
	(
		CategoryID int,
		CategoryName varchar(256),
		AccountID int,
		AccountNumber varchar(265),
		ExpenseAmount money,
		ExpenseMonth datetime,
		FundID int,
		SortOrder int
	)
	--create index ExpenseMonth on #lookUp(ExpenseMonth)
	--create index CategoryIDExpenseMonth on #lookUp(CategoryID, ExpenseMonth)
	--create index AccountIDExpenseMonth on #lookUp(AccountID, ExpenseMonth)

	insert into #lookUp
		select 
			fc.[ID] as CategoryID,
			fc.[Name] as CategoryName,
			fa.[ID] as AccountID,
			fa.Number + ' - ' + [Description] as AccountNumber,
			isnull(mfaa.amount, 0) as ExpenseAmount,
			mfaa.MonthEndingDate as ExpenseMonth,
			mfaa.FundID,
			fc.SortOrder
		from 
			MonthlyFundAccountActuals mfaa (nolock)
			inner join FinAccount fa (nolock) on mfaa.AccountID = fa.[ID]
			inner join FinCategory fc (nolock) on fc.[ID] = fa.FinCategoryID	
			inner join #TempFundCollection af (nolock) on mfaa.FundID = af.FundID
		where
			fc.[Name] not in ('INDIRECT COSTS', 'INVESTMENT INCOME', 'OTHER INCOME')
 			and mfaa.MonthEndingDate between @expenseDateFrom and @expenseDateTo
			and (fc.[ID] = @categoryID or @categoryID = 0) 
			and (mfaa.AccountID = @accountID or @accountID = 0)
			and ((mfaa.FundID = @fundID) or (@fundID = 0))
			
		order by
			fc.[ID], MonthEndingDate, AccountID

	if @expenseDateFrom = '1900-01-01 00:00:00'
	begin
		select
			dr.MonthEndingDate as ExpenseMonth,
			sum(IsNull(l.ExpenseAmount,0)) as TotalExpenses
		into #tmp1
		from
			#lookUp l
			right outer join #dateRange dr on l.ExpenseMonth = dr.MonthEndingDate 
		group by
			dr.MonthEndingDate
		order by
			dr.MonthEndingDate asc

		declare @firstMonthWithExpenses datetime
		set @firstMonthWithExpenses = (select min(ExpenseMonth) from #tmp1 where TotalExpenses <> 0)

		delete	#dateRange
		where	MonthEndingDate < @firstMonthWithExpenses

		delete	#lookUp
		where	ExpenseMonth < @firstMonthWithExpenses
		drop table #tmp1
	end

	declare @t4 datetime
	set @t4 = current_timestamp
	print 'Step_3: ' + cast(datediff(ss, @t2, @t4) as varchar)

	-- Retrieve category information for each month-end date within the date range specified. This information will be
	-- used to generate multiple tables in the resultset and as such is stored in a table variable.
	-- Note that we need an entry for each category for each expense month. This is achieved in two steps:
	-- Step 1: use a cross join between the table which contains the months and the table which contains the category
	-- information. This gives us the cartesian product as required. The only thing to be careful about is not to
	-- include any column in the select list which may produce more results in the product than is required. This forces
	-- us to set the expense amount to 0 in this step.
	-- Step 2: update the expense amount (set to 0 in step 1) for each unique combination of category and expense month.
	-- I am sure there are other ways of achieving the same, but all of them either involve explicit iteration or cursors,
	-- neither of which would be as fast as simple using the intelligence of T-SQL itself.

	create table #accountCategory
	(
		CategoryID int,
		CategoryName varchar(256),
		SortOrder int,
		ExpenseAmount money,
		ExpenseMonth datetime,
		AccountID int,
		AccountNumber varchar(265)
	)
	--create index CategoryIDExpenseMonth on #accountCategory(CategoryID, ExpenseMonth)
	--create index AccountIDExpenseMonth on #accountCategory(AccountID, ExpenseMonth)

	declare @t5 datetime
	set @t5 = current_timestamp
	print 'Step_5: ' + cast(datediff(ss, @t4, @t5) as varchar)

	-- Retrieve account information for each month-end date within the date range specified. This information will be
	-- used to generate multiple tables in the resultset and as such is stored in a table variable.
	-- Note that we need an entry for each account for each expense month. This is achieved in two steps:
	-- Step 1: use a cross join between the table which contains the months and the table which contains the account
	-- information. This gives us the cartesian product as required. The only thing to be careful about is not to
	-- include any column in the select list which may produce more results in the product than is required. This forces
	-- us to set the expense amount to 0 in this step.
	-- Step 2: update the expense amount (set to 0 in step 1) for each unique combination of account and expense month.
	-- I am sure there are other ways of achieving the same, but all of them either involve explicit iteration or cursors,
	-- neither of which would be as fast as simple using the intelligence of T-SQL itself.

	-- Step 1:
	insert into #accountCategory
		select distinct CategoryID, CategoryName, SortOrder, 0 as ExpenseAmount, dr.MonthEndingDate, AccountID, AccountNumber
			from #dateRange dr
				cross join #lookUp lu
				--here was Cartesian Join..the where clause fixes the problem JML 0914-2007:
				where dr.MonthEndingDate = lu.ExpenseMonth

	-- Step 2:
	update c
		set ExpenseAmount = (select sum(isnull(ExpenseAmount, 0)) from #lookUp
			where AccountID = c.AccountID and ExpenseMonth = c.ExpenseMonth)
		from #accountCategory c
			inner join #lookUp lu on lu.AccountID = c.AccountID and lu.ExpenseMonth = c.ExpenseMonth

	-- The fourth table in the resultset contains account information for each expense month.
	select
		AccountID,
		AccountNumber,
		CategoryID,
		CategoryName,
		SortOrder,
		convert(DateTime, ExpenseMonth, 101) as ExpenseMonth,
		IsNull(ExpenseAmount,0) as ExpenseAmount
	from
		#accountCategory
	order by
		SortOrder, AccountID, CategoryID, ExpenseMonth

	-- The fifth table in the resultset is the agreegated expense for each account.
	select
		AccountID,
		AccountNumber,
		CategoryID,
		CategoryName,
		SortOrder,
		sum(IsNull(ExpenseAmount,0)) as ExpenseAmount
	from
		#accountCategory
	group by
		AccountID, AccountNumber, CategoryID, CategoryName, SortOrder
	order by
		SortOrder, AccountID

	declare @t6 datetime
	set @t6= current_timestamp
	print 'Step_6: ' + cast(datediff(ss, @t5, @t6) as varchar)

	drop table #accountCategory
	drop table #lookUp
	drop table #dateRange
	drop table #TempFundCollection
end





GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Altering [dbo].[GetProtocolProcesses]'
GO

/******************************************************************
* Name:			GetProtocolProcesses
* Purpose:		Retrieves a list of ProtocolProcesses based on the Protocol's
*					id passed in as a parameter.
*
* PARAMETERS
* Name    						Description					
* -------------  				-------------------------------------------
* @protocolId					The Id of the Protocol whose ProtocolProcess
*								are to be retrieved.
******************************************************************/

ALTER Procedure [dbo].[GetProtocolProcesses] (
		@protocolId		INTEGER	
)
AS
BEGIN

	SET NOCOUNT ON

	Select			[Id],
					ProtocolId, 
					[Name], 
					Type,
					Status, 
					Locked,
					LastLockedVersion,
					ReceivedDate, 
					ApprovalDate,
					ExpirationDate,
					PrimaryReviewerId,
					SecondaryReviewerId,
					SubmitterId,
					CreateDate,
					LastModifiedDate,
					LastModifiedByUserId,
					SubmittedDate,
					ShowStaff,
					ShowAttachments,
					RexIRBStatusId,
					BeenSubmitted,
					HasBeenLocked,
					Resubmission		
					
			FROM ProtocolProcess
			WHERE	ProtocolId = @protocolId
	
END



GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Altering [dbo].[GetStandardReportList]'
GO
/******************************************************************      
* Name:   [GetStandardReportList]      
* Purpose:  Retrieves matching rows joining with passed in admPersonIds.       
* Note: This procedure is not used anywhere in the COI application as stadard reports has been removed.     
* PARAMETERS(IN)      
* Name          Description           
* -------------      -------------------------------------------      
* @xml       xml Document containing list of Ids(REQUIRED)        
*********************************************************************/      
      
ALTER PROCEDURE [dbo].[GetStandardReportList]      
(      
@xml text      
)      
AS BEGIN      
SET NOCOUNT ON      
      
 declare @xmlDoc int        
 declare @admPersonIds table (Sequence int identity, [ID] int)        
 exec sp_xml_preparedocument @xmlDoc output, @xml        
 insert into @admPersonIds select [PersonId] from openxml(@xmlDoc, '//IdList', 2) with (PersonId int)        
 exec sp_xml_removedocument @xmlDoc      
      
SELECT adp.[Id],      
    adp.[lastname]+', '+adp.[firstname] as [Name],      
       adp1.[lastname]+', '+adp1.[firstName] as [Supervisor],  
    adp.Title,    
    coi.[Id] as [COIId],    
       coi.[PolicyViolation] ,      
       coi.[HasOutsideActivities] ,      
       coi.[HasEquityInterests] ,      
       coi.[HasFamilyAssociations] ,      
       coi.[OtherActivity] ,      
       coi.[DateSubmitted]             
     FROM @admPersonIds tempTable  
  Left JOIN AdmPerson adp   
  on tempTable.[Id] = adp.[Id]  
  Left Outer JOIN ConflictOfInterest coi   
  on tempTable.[Id]= coi.[admPersonId]  
  AND coi.[Id]= (Select Max(Id)as LatestCOIId from conflictofinterest where admPersonId=adp.[Id] and status <> 'COISTATUS_TERMINATED')  
 Left Outer Join  COI_Hierarchy_Map chm  
  on adp.[Id]= chm.[childId]  
    Left Outer Join AdmPerson adp1   
  on adp1.[Id]= chm.[ParentId]     
       
       
END  
  

GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Altering [dbo].[GetCOIUserHierarchyList]'
GO

/******************************************************************              
* Name:   [GetCOIUserHierarchyList]              
* Purpose:  Retrieves matching records(joining with admperson,conflictofinterest tables).  
*              
* PARAMETERS(IN)              
* Name          Description                   
* -------------      -------------------------------------------              
* @xml       xml Document containing list of Ids(REQUIRED)                
*********************************************************************/              
              
ALTER PROCEDURE [dbo].[GetCOIUserHierarchyList]              
(              
@xml text              
)              
AS BEGIN              
SET NOCOUNT ON              
              
 declare @xmlDoc int                
 declare @admPersonIds table (Sequence int identity, [ID] int,[SupervisorId] int)                
 exec sp_xml_preparedocument @xmlDoc output, @xml                
 insert into @admPersonIds select [Id],[SupervisorId] from openxml(@xmlDoc, '//IdList', 2) with (Id int,SupervisorId int)                
 exec sp_xml_removedocument @xmlDoc              
              
SELECT adp.[Id],              
     adp.[lastname]+', '+adp.[firstname] as [Name],              
     adp1.[lastname]+', '+adp1.[firstName] as [Supervisor],            
  coi.[Id] as [COIId],            
     coi.[PolicyViolation],              
     coi.[HasOutsideActivities],              
     coi.[HasEquityInterests],              
     coi.[HasFamilyAssociations],              
     coi.[OtherActivity],              
     coi.[LastNotified],              
     coi.[DateSubmitted],              
     coi.[DateReviewed],
	 coi.[Status]           
             
  FROM @admPersonIds tempTable          
  Inner JOIN AdmPerson adp           
  on tempTable.[Id] =adp.[Id]          
  Left Outer JOIN ConflictOfInterest coi           
  on tempTable.[Id]= coi.[admPersonId]          
  AND coi.[Id]= (Select Max(Id)as LatestCOIId from conflictofinterest where admPersonId=adp.[Id] and status <> 'COISTATUS_TERMINATED')          
  Left Outer Join AdmPerson adp1           
  on adp1.[Id] =tempTable.[SupervisorId]    
              
END    
      
   


GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Altering [dbo].[GetUserContext]'
GO
/******************************************************************
* VSS File Path: $Archive: /PHSRAG/Applications/WebApplications/Insight_2.2.0/Database/MissingStoredProcs/SPsMissingFrom220VSS.sql $
* Name:  GetUserContext
* Purpose:  
* Gets user context information based on a domain user name.
*
* PARAMETERS
* Name    				Description					
* -------------  		---------------------------------------
* @userName			The user's userName
*
* RESULT SET
* Name    			Description					
* --------------	-------------------------------------------
* User Context information				n/a
*
*
* RETURN VALUE
* Value    			Description					
* --------------	-------------------------------------------
* N/A				N/A
*
******************************************************************/
ALTER Procedure [dbo].[GetUserContext] (
		@userName			AS VARCHAR (36)
)
AS

BEGIN

	SET NOCOUNT ON

	Declare @activeModuleBitMask int

	Select @activeModuleBitMask = sum(BitValue) from ModuleType
	where IsActive = 1

	Set @activeModuleBitMask = IsNull(@activeModuleBitMask, 0)
	
	-- Retrieve application user information	 
	SELECT au.Id	AS ApplicationUserId
		,au.IsActiveBitmask
		,du.Id AS DomainUserId
		,du.Username
		,p.FirstName
		,p.LastName
		,p.Id as AdmPersonId
		,au.ModuleBitmask & @activeModuleBitMask as ModuleBitmask
		,au.ModuleRoleBitmask
		,aea.EmailAddress
	FROM FwkApplicationUser au
	INNER JOIN FwkDomainUser du
		ON au.FwkDomainUserId = du.Id
	INNER JOIN AdmPerson p
		ON du.Id = p.FwkDomainUserId
	LEFT JOIN AdmEmailAddress aea
		ON p.Id = aea.AdmPersonId AND aea.AdmEmailAddressTypeId = 1
	WHERE du.Username = @userName

	SET NOCOUNT OFF
END

GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Altering [dbo].[CreateProtocolProcessWorkFlowMap]'
GO




ALTER PROCEDURE dbo.CreateProtocolProcessWorkFlowMap (
	/* Param List */
	@ProtocolProcessID int,
	@ExecutionID int,
	@Type VARCHAR (6)
) 
AS
	SET NOCOUNT ON
	
	DECLARE @errorCode int

	INSERT INTO
	ProtocolProcess_WorkFlow_Map
	(ExecutionID, ProtocolProcessID, [Type])
	VALUES
	(@ExecutionID, @ProtocolProcessID, @Type)
	
	IF @Type = 'INIT' BEGIN
		UPDATE ProtocolProcess SET BeenSubmitted = 1 WHERE ID = @ProtocolProcessId
	END
	
	SET @errorCode = @@ERROR
	
	IF @errorCode <> 0 
	BEGIN           
            RAISERROR('Unable to create ProtocolProcess_WorkFlow_Map record', 16, 1)
            RETURN @errorCode
        END
	
	



GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Creating [dbo].[spCdsNCreatePerPayType]'
GO
SET QUOTED_IDENTIFIER OFF
GO


/******************************************************************************
**		VSS File: $/spCdsNCreatePerPayType.sql 
**		Name: spCdsNCreatePerPayType	
**		Desc: 	This procedure creates a record in the 
**				PerPayType table
**			
**		Return values: None
** 
**		Called by:   
**			
*******************************************************************************
**		Change History
*******************************************************************************
**		Date:		Author:				Description:
**		--------	--------			---------------------------------------
**	
*******************************************************************************/
CREATE Procedure dbo.spCdsNCreatePerPayType (
	/* Param List */
	@name				VARCHAR(256),
	@description		VARCHAR(512)
)	
AS	
BEGIN 

	SET NOCOUNT ON

	DECLARE @_errorCode	INT

	SET @_errorCode  = 0

	-- Insert the AdmPerson
	INSERT INTO PerPayType	(
								Name, 
								Description,
								DateCreated
							)
	VALUES					(
								@name,	
								@description,
								GETDATE()
							)

	SET @_errorCode = @@ERROR

	IF @_errorCode <> 0 BEGIN
		RAISERROR('Unable to create PerPayType record for PerPayType %s', 16, 1, @name)
		RETURN @_errorCode
	END

END


GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Creating [dbo].[UpdateClinicalTrialBudgetStaffIdForTasks]'
GO
SET QUOTED_IDENTIFIER ON
GO

--We update the item in the clinicaltrialbudgettask table to make sure each task will have the correct staff id associated with it
--Otherwise, either no staff id will be associated with it or the wrong one will be, this makes sure that
--the correct id is there. 
CREATE PROCEDURE [dbo].[UpdateClinicalTrialBudgetStaffIdForTasks] (
	@oldStaffId int, 
	@budgetTaskId int, 
	@budgetIdOld int, 
	@budgetIdNew int
)
AS
BEGIN
	SET NOCOUNT ON

   

	IF EXISTS ( SELECT null FROM ClinicalTrialBudgetTask WHERE Id = @budgetTaskId )
	BEGIN
	-- Update
    
	UPDATE ClinicalTrialBudgetTask
	SET 	ClinicalTrialBudgetStaffId = (Select Id From ClinicalTrialBudgetStaff where StudyStaffRoleCode = (select StudyStaffRoleCode FROM ClinicalTrialBudgetStaff WHERE id = @oldStaffId and ClinicalTrialBudgetId = @budgetIdOld) and ClinicalTrialBudgetId = @budgetIdNew	)	
	WHERE Id = @budgetTaskId 

	IF @@ERROR <> 0
		BEGIN
			RAISERROR ('Failed to update clinical trial budget task. Error = %s.', 16, 1, @@ERROR)
			RETURN
		END
	END
	END 


GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Altering [dbo].[SaveProtocolProcess]'
GO

/******************************************************************
* Name:			SaveProtocolProcess
* Purpose:		Saves a Protocol Process with the values passed in. If
*					the Id parameter passed in is 0, it will insert a new
8					record, otherwise it updates the existing one.
*
* PARAMETERS
* Name    						Description					
* -------------  				-------------------------------------------
*		@id						Id of the Process. 0 will do an insert.
*		@protocolId				ID of the Protocol record who owns this Process
*		@name					Name of the Process
*		@type					Process Type (AM, CR, etc...)
*		@status					Status of the Process
*		@locked					Locked Flag
*		@lastLockedVersion		LastLocked Protocol Version of this process
*		@receivedDate			Date the process was received
*		@approvalDate			Date this process was approved by the IRB
*		@expirationDate			Expiration date of this process (used to determine CRs)
*		@primaryReviewerId		AdmPersonID of the primary IRB reviewer person
*		@secondaryReviewerId	AdmPersonID of the secondary IRB reviewer person
*		@submitterId			FwkDomainUser ID of the person submitting this Process (used in WF)
*		@latestProtocolVersionId ProtocolVersionID of the latest version
*		@lastModifiedUserId		FwkDomainUserId of the person to last modify this process
******************************************************************/

ALTER Procedure [dbo].[SaveProtocolProcess] (
		@id				INTEGER = 0,
		@protocolId		INTEGER ,
		@name			Varchar(12) ,
		@type			Varchar(256) ,
		@status			Varchar(256) ,	
		@locked			BIT = 1,
		@lastLockedVersion INTEGER = 0 ,
		@receivedDate	DateTime ,
		@approvalDate	DateTime ,
		@expirationDate DateTime ,
		@primaryReviewerId INTEGER ,
		@secondaryReviewerId INTEGER ,
		@submitterId	INTEGER ,
		@lastModifiedUserId INTEGER = 0,
		@lastModifiedDate DateTime = NULL,
		@submittedDate	DateTime,
		@showStaff bit,
		@showAttachments bit,
		@rexIRBStatusId int = NULL,
		@beenSubmitted bit,
		@hasBeenLocked bit,
		@resubmission bit
)
AS
BEGIN

	SET NOCOUNT ON
	
	
	IF @lastModifiedDate IS NULL
	BEGIN
		SET @lastModifiedDate  = GETDATE()
	END		 
		
	-- if it's zero, then insert
	IF @id = 0 
		BEGIN
		
		INSERT INTO ProtocolProcess (	
								ProtocolId,
								[Name],
								Type,
								Status,
								Locked,
								LastLockedVersion,
								ReceivedDate,
								ApprovalDate,
								ExpirationDate,
								PrimaryReviewerId,
								SecondaryReviewerId,
								SubmitterId,
								CreateDate,
								LastModifiedDate,
								LastModifiedByUserId,
								SubmittedDate,
								ShowStaff,
								ShowAttachments,
								RexIRBStatusId,
								BeenSubmitted,
								HasBeenLocked,
								Resubmission
								)
				Values
							(	@protocolId,
								@name,
								@type,
								@status,
								@locked,
								@lastLockedVersion,
								@receivedDate,
								@approvalDate,
								@expirationDate,
								@primaryReviewerId,
								@secondaryReviewerId,
 								@submitterId,
								GETDATE(),
								GETDATE(),
								@lastModifiedUserId,
								@submittedDate,
								@showStaff,
								@showAttachments,
								@rexIRBStatusId,	
								@beenSubmitted,
								@hasBeenLocked,
								@resubmission )

		SELECT IDENT_CURRENT('ProtocolProcess')

		END
		IF @@ERROR <> 0 GOTO ERROR_HANDLER
	
	-- else update ony the Name and Script of the existing one.
	ELSE
		UPDATE ProtocolProcess SET	[Name]	= @name,
							Type	= @type,
							Status	= @status,
							Locked	= @locked,
							LastLockedVersion = @lastLockedVersion,
							ReceivedDate = @receivedDate,
							ApprovalDate = @approvalDate,
							ExpirationDate	= @expirationDate,
							PrimaryReviewerId = @primaryReviewerId,
							SecondaryReviewerId = @secondaryReviewerId,
							LastModifiedByUserId = @lastModifiedUserId,
							LastModifiedDate = @lastModifiedDate,
							SubmittedDate = @submittedDate,
							SubmitterId = @submitterId,
							ShowStaff = @showStaff,
							ShowAttachments = @showAttachments,
							RexIRBStatusId = @rexIRBStatusId,
							BeenSubmitted = @beenSubmitted,
							HasBeenLocked = @hasBeenLocked,
							Resubmission = @resubmission

			WHERE Id = @id
	
		IF @@ERROR <> 0 GOTO ERROR_HANDLER

	SELECT @id	

	ERROR_HANDLER:
		RAISERROR('Unable to Save ProtocolProcess', 16, 1)
		RETURN
		
END


GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Altering [dbo].[GetWorkflowHistory]'
GO
/************************************************************************************************        
* Name:  [GetWorkflowHistory]                                                                  
* Purpose: This stored procedure gets the history of completed activities, associated with execution id       
*  id        
*          
* PARAMETERS          
* Name   Description        
* ------------------------- -----------------------------        
* @ProtocolProcessId    ProtocolProcess Id associated with the submission       
*        
************************************************************************************************        
*Call: [GetWorkflowHistory] 6        
************************************************************************************************/        
ALTER procedure [dbo].[GetWorkflowHistory]    
(        
 @protocolProcessId int         
)        
as        
begin        
set nocount on   
                      
Declare @executionId int  
Set @executionId = 0  
select  @executionId =Max(ExecutionId)    
       from     
       ProtocolProcess_WorkFlow_Map pwm    
       where pwm.ProtocolProcessId =@protocolProcessId
		And Rtrim(Ltrim(Type)) Like 'INIT'    
   
	if @executionId <> 0  
	BEGIN		            
		Exec [dbo].[GetWorkflowExecutionDetails] @executionId		
	END  

    Set @executionId = 0  
    select @executionId =Max(ExecutionId)    
    from     
    ProtocolProcess_WorkFlow_Map pwm    
    where pwm.ProtocolProcessId = @protocolProcessId
	And Rtrim(Ltrim(Type)) = 'RESUB'
	if @executionId <> 0
		BEGIN  
			Exec [dbo].[GetWorkflowExecutionDetails] @executionId			  
		END
Select rtrim(ltrim(adp.LastName)) +', '+rtrim(ltrim(adp.FirstName)) as SubmitterName   
  from admperson adp   
  inner join ProtocolProcess pp  
  on pp.SubmitterId = adp.FwkDomainUserId  
  Where pp.Id = @protocolProcessId
END

GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Creating [dbo].[MapExpiredRexAgreements]'
GO



/***************************************************************************
* Name:			MapExpiredRexAgreements
* Purpose:		Using table Stg_REX_ExpiredAgreements, map & seed Insight IDs, and validate
*				feed data.
*
* PARAMETERS
* Name				Description					
* -------------		-----------------------------------------------------------
* n/a
*
* ERRORS USED		Description
* -------------		-----------------------------------------------------
* n/a
*
* RETURN VALUE
* Value    			Description					
* --------------	------------------------------------------------------
* @_exitStatus		An exit status of either true or false
***************************************************************************/
CREATE PROCEDURE [dbo].[MapExpiredRexAgreements]
AS
BEGIN

	SET NOCOUNT ON

/*
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	R E P A I R  B A D  D A T A  F R O M  P S  F E E D
	Due to bad data we receive in the PeopleSoft Feed, the 3 updates
	below are necessary in order to correct the sponsor and award
	type data.  These corrections avoid unnecessary errors.
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*/
	-- Convert blank sponsors to be the 'sundry' sponsor
	update Stg_IE_DemogFeed_ExpiredAgreements set sponsor_name = 'SUNDRY' 
	where isNull(sponsor_name,'')='' or IsNumeric(isNull(sponsor_name,''))=1

	-- Convert the sponsor code to sundry for any fund with a sponsor name of
	-- sundry and the sponsor code is null or blank.
	update Stg_IE_DemogFeed_ExpiredAgreements set sponsor_code = '11' , sponsor_code_id = 11
	where isNull(sponsor_code,'')='' or isnull(sponsor_name,'') = 'SUNDRY' 

	-- Set the award type to 'misc/other' award type if it is null or blank.
	update Stg_IE_DemogFeed_ExpiredAgreements set award_type_code = 'M' 
	where isNull(award_type_code,'')='' 

	-- >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	-- E X I S T I N G  F U N D  A N D  F O L D E R  N U M B E R
	-- First map fund number to existing fund and agreement data
	-- >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

	UPDATE s
	SET AgrAgreementId = a.Id
		,folder_number = a.foldernumber
		,SvcEntityId = a.SvcEntityId
		,AgrBudgetContainerId = a.AgrBudgetContainerId
		,AgrBudgetContainerViewId = bcv.Id
		,AgrBudgetContainerViewId1 = bcv1.Id
		,AgrBudgetId = b.Id
		,AgrBudgetCount = (Select Count(*) from AgrBudget b3 
							where b3.AgrBudgetContainerViewId = bcv.Id 
									and b3.AgrBudgetTypeId = 1) --annual budget
		,AgrBudgetICRateId = bicr.id
		,FwkResourceId = a.FwkResourceId
		,AnnAnnotationContainerId = a.AnnAnnotationContainerId
		,SvcEntityFacilityMapId = afm.Id
		,AgrFundId = f.AgrFundID
		,AgrFundAgreementMapId = f.Id
		,BusinessUnitId = f.BusinessUnitId
		,Orig_AgrNumberSchemeTypeId = a.AgrNumberSchemeTypeId
		,Orig_AgrTransactionTypeId = a.AgrTransactionTypeId
		,Orig_AgrAgreementTypeId = a.AgrAgreementTypeId
		,Orig_AgrAgreementStatusTypeId = a.AgrAgreementStatusTypeId
		,Orig_PI_AdmPersonID = a.PIPersonID
		,Orig_RM_AdmPersonID = RM.AdmPersonID
		,Orig_CSR_AdmPersonID = CSRL.AdmPersonID
		,Orig_AdmSponsorId = spm.AdmSponsorId
		,Orig_fwkDomainOrganizationId = fdo.fwkDomainOrganizationId
		,Orig_finICBaseTypeId = bc.IndirectCostBaseId
		,Orig_AgrActivityTypeId = act.Id
		,Orig_FinAccountCycleTypeId = f.FinAccountCycleTypeId
		,Orig_AgrFundStatusTypeId = f.AgrFundStatusTypeId
		,Orig_AgrFundAwardTypeId = f.AgrFundAwardTypeId
		,Orig_AgrFundOverheadClassificationId = f.AgrFundOverheadClassificationId
		,Orig_AgrFundTypeId = f.AgrFundTypeId
		,Orig_AgrFundSubTypeId = f.AgrFundSubTypeId
		,Orig_AgrCostCenterId = cfm.AgrCostCenterId
		,Orig_AgrCostCenterStatusTypeId = cfm.AgrCostCenterStatusTypeId
		,Orig_AdmFacilityId = afm.AdmFacilityId
		,IsNewAgreement = 0
		,IsNewFund = 0
	from Stg_IE_DemogFeed_ExpiredAgreements s
	inner join AgrFund_AgrAgreement_Map f on f.Fundnumber = s.project_grant
	inner join AgrAgreement a on a.id = f.agragreementId and a.documentnumber = (Select max(a1.documentNumber) from AgrAgreement a1
															where a1.foldernumber = a.folderNumber 
																and a1.isAmendment = 0 and a1.IsCurrent=1)
	left outer join SvcEntity_FwkDomainOrganization_Map fdo on fdo.svcentityid = a.svcentityid and fdo.FwkOrganizationRelationshipTypeId = 1 -- Primary 
	left outer join SvcEntity_AdmAdministrator_Map RM on RM.svcentityid = a.svcentityid and RM.AdministratorTypeId = 1 -- RM admin
	left outer join SvcEntity_AdmAdministrator_Map CSRL on CSRL.svcentityid = a.svcentityid and CSRL.AdministratorTypeId = 2 -- CSRL admin
	left outer join SvcEntity_AdmFacility_Map afm on afm.svcentityid = a.svcentityid and afm.AdmFacilityRelationshipTypeId = 1 -- primary facility
	left outer join SvcEntity_AdmSponsor_Map spm on spm.svcentityid = a.svcentityid and spm.AdmSponsorRelationTypeId = 1 -- primary sponsor.
	left outer join AgrBudgetContainer bc on bc.Id = a.AgrBudgetContainerId
	left outer join AgrBudgetContainerView bcv on bcv.AgrBudgetContainerId = a.AgrBudgetContainerId and bcv.AgrBudgetViewTypeId = 3 --awarded
	left outer join AgrBudgetContainerView bcv1 on bcv.AgrBudgetContainerId = a.AgrBudgetContainerId and bcv.AgrBudgetViewTypeId = 1 --pending
	left outer join AgrBudget b on b.agrFundAgreeMapId = f.id
	left outer join AgrBudgetICRate bicr on bicr.AgrBudgetId = b.Id 
	left outer join AgrActivityType act on act.PSCode = s.activity_type_code
	left outer join AgrCostCenter_AgrFund_Map cfm on cfm.AgrFundAgreementMapId = f.Id
	left outer join AgrCostCenter cc on cc.Id = cfm.AgrCostCenterId 
	left outer join AgrCostCenterStatusType ccs on ccs.Id = cfm.AgrCostCenterStatusTypeId

	/*
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	A P P L Y  F U N D  A C T I V A T I O N  D A T E S  F R O M  I N F O E D
	PeopleSoft demog.txt does not have the fund activation dates so we are
	loading them from InfoEd and defaulting to effective date if the 
	activation date is not available.
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	*/
	update s 
	set activationDate = coalesce(s1.dtActivated,s.effective_date)	
	from Stg_IE_DemogFeed_ExpiredAgreements s
	left outer join Stg_IE_DemogFeed_InfoEdFunds s1 on s.project_grant = s1.sPSFundNumber

	/*
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	A P P L Y  F O L D E R  N U M B E R  F R O M  I N F O E D
	Folder numbers in PeopleSoft tend to be inaccurate, so where
	available, we are mapping the folder numbers to the appropriate
	fund numbers from InfoEd.
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	*/
	update s 
	set folder_number = left(s1.sFolderNumber,11)
		,activationDate = s1.dtActivated	
		,IsInfoEdFolderNumber = 1
	from Stg_IE_DemogFeed_ExpiredAgreements s
	inner join Stg_IE_DemogFeed_InfoEdFunds s1 on s.project_grant = s1.sPSFundNumber
	where (isnull(s.folder_number,'')='' or isnull(s.folder_number,'')<> left(s1.sFolderNumber,11)) and agragreementId is null
	/*
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	A P P L Y  F O L D E R  N U M B E R  F R O M  R E X  F E D
	Folder numbers in PeopleSoft tend to be inaccurate, so where
	available, we are mapping the folder numbers to the appropriate
	fund numbers from InfoEd.
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	*/
	update s 
	set folder_number = ea.FolderNumber
	from Stg_IE_DemogFeed_ExpiredAgreements s
	INNER JOIN Stg_Rex_ExpiredAgreement_FundMap fm on fm.FundNumber = s.project_grant
	INNER JOIN Stg_Rex_ExpiredAgreements ea on ea.Id = fm.AgrAgreementId

	-- >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	-- N E W  F U N D  O N  E X I S T I N G  F O L D E R  N U M B E R
	-- If the folder number data was not mapped through an existing
	-- fund number, try to map to an existing folder number.
	-- >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

	UPDATE s
	SET AgrAgreementId = a.Id
		,folder_number = a.foldernumber
		,SvcEntityId = a.SvcEntityId
		,AgrBudgetContainerId = a.AgrBudgetContainerId
		,AgrBudgetContainerViewId = bcv.Id
		,AgrBudgetContainerViewId1 = bcv1.Id
		,AgrBudgetId = b.Id
		,AgrBudgetCount = (Select Count(*) from AgrBudget b3 where b3.AgrBudgetContainerViewId = bcv.Id and b3.AgrBudgetTypeId = 1) --annual budget
		,AgrBudgetICRateId = bicr.id
		,FwkResourceId = a.FwkResourceId
		,AnnAnnotationContainerId = a.AnnAnnotationContainerId
		,SvcEntityFacilityMapId = afm.Id
		,AgrFundId = f.ID
		,BusinessUnitId = f.BusinessUnitId
		,Orig_FinAccountCycleTypeId = f.FinAccountCycleTypeId
		,Orig_AgrFundStatusTypeId = f.AgrFundStatusTypeId
		,Orig_AgrFundAwardTypeId = f.AgrFundAwardTypeId
		,Orig_AgrFundOverheadClassificationId = f.AgrFundOverheadClassificationId
		,Orig_AgrFundTypeId = f.AgrFundTypeId
		,Orig_AgrFundSubTypeId = f.AgrFundSubTypeId
		,Orig_AgrNumberSchemeTypeId = a.AgrNumberSchemeTypeId
		,Orig_AgrTransactionTypeId = a.AgrTransactionTypeId
		,Orig_AgrAgreementTypeId = a.AgrAgreementTypeId
		,Orig_AgrAgreementStatusTypeId = a.AgrAgreementStatusTypeId
		,Orig_PI_AdmPersonID = a.PIPersonID
		,Orig_RM_AdmPersonID = RM.AdmPersonID
		,Orig_CSR_AdmPersonID = CSRL.AdmPersonID
		,Orig_AdmSponsorId = spm.AdmSponsorId
		,Orig_fwkDomainOrganizationId = fdo.fwkDomainOrganizationId
		,Orig_finICBaseTypeId = bc.IndirectCostBaseId
		,Orig_AgrActivityTypeId = act.Id
		,Orig_AdmFacilityId = afm.AdmFacilityId
		,IsNewFund = case when f.id is null then 1 else 0 end
		,IsNewAgreement = 0
	from Stg_IE_DemogFeed_ExpiredAgreements s
	inner join AgrAgreement a  on a.FolderNumber = s.folder_number  
									and a.documentNumber = (Select max(a1.documentNumber) from AgrAgreement a1
															where a1.foldernumber = a.foldernumber
																and a1.isAmendment = 0 and a1.IsCurrent=1)
	left outer join SvcEntity_FwkDomainOrganization_Map fdo on fdo.svcentityid = a.svcentityid and fdo.FwkOrganizationRelationshipTypeId = 1 -- Primary 
	left outer join SvcEntity_AdmAdministrator_Map RM on RM.svcentityid = a.svcentityid and RM.AdministratorTypeId = 1 -- RM admin
	left outer join SvcEntity_AdmAdministrator_Map CSRL on CSRL.svcentityid = a.svcentityid and CSRL.AdministratorTypeId = 2 -- CSRL admin
	left outer join SvcEntity_AdmFacility_Map afm on afm.svcentityid = a.svcentityid and afm.AdmFacilityRelationshipTypeId = 1 -- primary facility
	left outer join SvcEntity_AdmSponsor_Map spm on spm.svcentityid = a.svcentityid and spm.AdmSponsorRelationTypeId = 1 -- primary sponsor.
	left outer join AgrBudgetContainer bc on bc.Id = a.AgrBudgetContainerId
	left outer join AgrBudgetContainerView bcv on bcv.AgrBudgetContainerId = a.AgrBudgetContainerId and bcv.AgrBudgetViewTypeId = 3 --awarded
	left outer join AgrBudgetContainerView bcv1 on bcv.AgrBudgetContainerId = a.AgrBudgetContainerId and bcv.AgrBudgetViewTypeId = 1 --pending
	left outer join AgrBudget b on b.AgrBudgetContainerViewId = bcv.Id and b.AgrBudgetTypeId = 1 --annual budget
									and b.Id = (select max(b1.Id) from AgrBudget b1 
												where b1.AgrBudgetContainerViewId = b.AgrBudgetContainerViewId 
													and b1.AgrBudgetTypeId = b.AgrBudgetTypeId
													and b1.startDate = coalesce(s.dtBudgetStart,s.dtprojectstart,'1/1/1900'))
	left outer join AgrBudgetICRate bicr on bicr.AgrBudgetId = b.Id 
	left outer join AgrActivityType act on act.PSCode = s.activity_type_code
	left outer join AgrFund f on f.FundNumber = s.project_grant
	where IsNull(s.AgrFundId,0)=0

	/*
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	M A P  N E W  T Y P E  D A T A
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	*/
	UPDATE	Stg_IE_DemogFeed_ExpiredAgreements
	SET		/*
			>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
			*** Default to NEW Can't assign because we don't know if 
			it is NEW, NON-COMPETE, TRANSFER, COMPETING RENEWAL, or SUPPLIMENT.
			>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
			*/
			agrTransactionTypeId = coalesce(Orig_AgrTransactionTypeId,1)
													 -- Default NEW transaction
			/*
			>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
			*** Default to AWARDED. Can't assign because we don't know if 
			it is PENDING, APPROVED, AWARDED, ACTIVE, or CLOSED, etc.
			>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
			*/

			,AgrAgreementStatusTypeId = coalesce(Orig_AgrAgreementStatusTypeId
													,case when IsNull(effective_status,'')='A' then 
														(select ID from agragreementStatusType where [name] = 'Awarded')
													 else 
														(select ID from agragreementStatusType where [name] = 'Closed')
													 end) 
													-- Default to original status, else AWARDED if active and closed if NOT Active.
			/*
			>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
			M A P  A G R E E M E N T  T Y P E S
			Map the agreement types to IDs in Insight AgrAgreementType table
			from the award type code of the fund.
			>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
			*/
			,AgrAgreementTypeId = coalesce(
					(Select fat.AgrAgreementTypeId from AgrFundAwardType fat
					 where fat.[name] = isNull(award_type_code,''))
					,Orig_AgrAgreementTypeId
					,1/* Grant is the default if all else fails */)
			/*
			>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
			M A P  F U N D  A W A R D  T Y P E S
			Map the fund award types to IDs in Insight AgrFundAwardType table.
			>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
			*/
			,AgrFundAwardTypeId = 
									(select AgrFundAwardType.Id from AgrFundAwardType 
									where AgrFundAwardType.[name] = isNull(award_type_code,''))

			,AgrFundTypeId = 1 --Research

			/*
			>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
			M A P  I C  B A S I S  C O D E S
			Map the IC basis codes to IDs in Insight finICBaseType table.
			>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
			*/
			,finICBaseTypeId = coalesce(
								(select p.finICBaseTypeId from FinPSICBaseType p 
								 where p.[id] = isNull(ic_base_int,0))
								,1/* Default to MTDC if nothing else */)

			-- if can't map, default to miscellaneous activity type.
			,AgrActivityTypeId = coalesce(
								 (Select AgrActivityType.Id from AgrActivityType 
								  where AgrActivityType.PSCode = IsNull(activity_type_code,''))
								 ,21) 

			,AgrFundOverheadClassificationId = 
								(Select AgrFundOverheadClassification.id from AgrFundOverheadClassification 
								 where AgrFundOverheadClassification.PSCode = IsNull(Fund_code,''))

			,AgrFundStatusTypeId = 
								(Select AgrFundStatusType.Id from AgrFundStatusType 
								 where  AgrFundStatusType.[name] = IsNull(effective_status,''))

			,FinAccountCycleTypeId = coalesce(
								(Select FinAccountCycleType.Id from FinAccountCycleType 
								 where	upper(left(FinAccountCycleType.[name],1)) = 
										Upper(ltrim(rtrim(IsNull(acct_cycle_code,'')))))
								, Orig_FinAccountCycleTypeId)

			,fwkDomainOrganizationId = 
								(select Id from fwkDomainOrganization 
								 where fwkDomainOrganization.Institution = IsNull(resp_inst,'')
									and fwkDomainOrganization.ChiefCode = IsNull(dept_code,''))

			-- Map the PI ID from first the name conversion table, then the original if it exists
			-- and matches the last name, otherwise name match exactly on last name and 
			-- first name from PeopleSoft.
			,PI_AdmPersonId =	coalesce(
								 (Select l.AdmPersonId from PINameToPersonId l 
									Where l.lastname = IsNull(mgr_last_name,'') and l.firstname = IsNull(mgr_first_name,''))
								,(select ap.Id from admperson ap
										  where  ap.Id = Orig_PI_AdmPersonId and ap.lastname = IsNull(mgr_last_name ,'')
											and Orig_PI_AdmPersonId is not null)								
								,(Select min(s.Id) from
									(select Id,len(ltrim(rtrim(firstname))) as FirstNameLength from admPerson 
									where lastname = IsNull(mgr_last_name,'') 
										and firstname = left(IsNull(mgr_first_name,''),len(ltrim(rtrim(firstname))))) s) )

			,AdmSponsorId =	coalesce(Orig_AdmSponsorId
									,(Select min(spsr.Id) from AdmSponsor spsr where spsr.[name] = IsNull(sponsor_name,'')
									  or spsr.[Shortname] = IsNull(sponsor_name,'') or spsr.[Description] = IsNull(sponsor_name,'')))

			,AgrCostCenterId = (Select min(ac.Id)  FROM AgrCostCenter ac 
								Where ac.Number = IsNull(Cost_Center,'')  
									and ((IsNull(resp_inst,'')='MGH' and ac.agrcostcentersystemtypeid = 1)
										or(IsNull(resp_inst,'') = 'BWH' and ac.agrcostcentersystemtypeid = 2)))

			,AgrCostCenterStatusTypeId = (Select AgrCostCenterStatusType.Id from AgrCostCenterStatusType 
								 where  AgrCostCenterStatusType.[name] = IsNull(effective_status,''))

			,AdmFacilityId = (Select AdmFacility.id from AdmFacility where AdmFacility.PSCode = IsNull(location_code,''))

			,BusinessUnitId = (Select AdmBusinessUnit.Id from AdmBusinessUnit where PSCode = cast(IsNull(Business_unit,0) as varchar))

			,AgrFundId = (Select AgrFund.Id from AgrFund where AgrFund.FundNumber = IsNull(project_grant,''))
			,IsAgreementMaintained = --1
				case when IsInInfoED = 1 then 0 else 1 end
			,IsNewFund = case when exists(Select 1 from AgrFund where AgrFund.FundNumber = IsNull(project_grant,'')) Then 0 else 1 end
			,IsCurrentFund = 0 -- Not the current fund on the agreement.
			,IsChanged = 0 -- Not changed
			,IsNewCostCenter = 0 --Not New Cost Center
			,IsNewSponsor = 0 -- Not New Sponsor
			,IsValid = 1 -- Valid data
	/*
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	D E T E C T  N E W  S P O N S O R 
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	*/
	UPDATE	Stg_IE_DemogFeed_ExpiredAgreements
	SET		IsNewSponsor = 1
	WHERE	AdmSponsorId is null and rtrim(ltrim(isnull(sponsor_name,'')))<> ''
			and IsAgreementMaintained = 1
	/*
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	D E T E C T  N E W  C O S T  C E N T E R 
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	*/
	UPDATE	Stg_IE_DemogFeed_ExpiredAgreements
	SET		IsNewCostCenter = 1
	WHERE	AgrCostCenterId is null and rtrim(ltrim(isnull(cost_center,'')))<> ''
			and IsNull(resp_inst,'') = 'BWH'

	/*
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	D E T E C T  E R R O R S
	Look for stuff that does not map
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	*/
	UPDATE	Stg_IE_DemogFeed_ExpiredAgreements
	SET		IsValid = 0
	Where
		   (isNull(PI_AdmPersonId,0) = 0 and IsAgreementMaintained = 1)
		or (isNull(AdmSponsorId,0) = 0 and IsNewSponsor = 0)
		or isNull(agrTransactionTypeId,0) = 0
		or isNull(AgrAgreementStatusTypeId,0) = 0
		or isNull(AgrAgreementTypeId,0) = 0
		or isNull(finICBaseTypeId,0) = 0
		or isNull(AgrActivityTypeId,0) = 0
		or isNull(FinAccountCycleTypeId,0) = 0
		or isNull(fwkDomainOrganizationId,0) = 0
		or (isNull(AgrCostCenterId,0) = 0 and IsNewCostCenter = 0 and IsNull(resp_inst,'') = 'BWH')
		or isNull(AgrFundAwardTypeId,0) = 0
		or isNull(AgrFundOverheadClassificationId,0) = 0
		or isNull(AgrFundStatusTypeId,0) = 0
		or isNull(AgrCostCenterStatusTypeId,0) = 0
		or isNull(BusinessUnitId,0) = 0

	/*
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	S E E D  I D s
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	*/

	IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'tmpSeededAgrIDs')
		DROP TABLE tmpSeededAgrIDs

	IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'tmpSeededSvcIDs')
		DROP TABLE tmpSeededSvcIDs

	IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'tmpSeededFundSvcIDs')
		DROP TABLE tmpSeededFundSvcIDs

	IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'tmpSeededFwkIDs')
		DROP TABLE tmpSeededFwkIDs

	IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'tmpSeededBgtIDs')
		DROP TABLE tmpSeededBgtIDs

	IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'tmpSeededAnnIDs')
		DROP TABLE tmpSeededAnnIDs

	DECLARE	@_agreementSeed		int
	DECLARE	@_entitySeed		int
	DECLARE	@_resourceSeed		int
	DECLARE	@_budgetContainerSeed		int
	DECLARE	@_annotationSeed	int

	IF (SELECT Count(Id) FROM AgrAgreement) = 0
		SET	@_agreementSeed		= 1
	ELSE
		SET	@_agreementSeed		= IDENT_CURRENT('AgrAgreement') + 1

	IF (SELECT Count(Id) FROM SvcEntity) = 0
		SET	@_entitySeed		= 1
	ELSE
		SET	@_entitySeed		= IDENT_CURRENT('SvcEntity') + 1

	IF (SELECT Count(Id) FROM FwkResource) = 0
		SET	@_resourceSeed		= 1
	ELSE
		SET	@_resourceSeed		= IDENT_CURRENT('FwkResource') + 1

	IF (SELECT Count(Id) FROM AgrBudgetContainer) = 0
		SET	@_budgetContainerSeed		= 1
	ELSE
		SET	@_budgetContainerSeed		= IDENT_CURRENT('AgrBudgetContainer') + 1

	IF (SELECT Count(Id) FROM AnnAnnotationContainer) = 0
		SET	@_annotationSeed	= 1
	ELSE
		SET	@_annotationSeed	= IDENT_CURRENT('AnnAnnotationContainer') + 1

	/*
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	F U N D  S E E D S
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	*/
	IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'tmpSeededFundIDs')
		DROP TABLE tmpSeededFundIDs

	IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'tmpSeededFundAgreeMapIDs')
		DROP TABLE tmpSeededFundAgreeMapIDs

	IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'tmpSeededBudgetContainerViewIDs')
		DROP TABLE tmpSeededBudgetContainerViewIDs

	IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'tmpSeededBudgetIDs')
		DROP TABLE tmpSeededBudgetIDs

	DECLARE	@_fundSeed					int
	DECLARE	@_fundAgreeMapSeed			int
	DECLARE	@_budgetContainerViewSeed	int
	DECLARE	@_budgetSeed				int

	IF (SELECT Count(Id) FROM AgrFund) = 0
		SET	@_fundSeed	= 1
	ELSE
		SET	@_fundSeed	= IDENT_CURRENT('AgrFund') + 1

	IF (SELECT Count(Id) FROM AgrFund_AgrAgreement_Map) = 0
		SET	@_fundAgreeMapSeed	= 1
	ELSE
		SET	@_fundAgreeMapSeed	= IDENT_CURRENT('AgrFund_AgrAgreement_Map') + 1

	IF (SELECT Count(Id) FROM AgrBudgetContainerView) = 0
		SET	@_budgetContainerViewSeed	= 1
	ELSE
		SET	@_budgetContainerViewSeed	= IDENT_CURRENT('AgrBudgetContainerView') + 1

	IF (SELECT Count(Id) FROM AgrBudget) = 0
		SET	@_budgetSeed	= 1
	ELSE
		SET	@_budgetSeed	= IDENT_CURRENT('AgrBudget') + 1
	/*
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	C O S T  C E N T E R  S E E D S
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	*/
	IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'tmpSeededCCIDs')
		DROP TABLE tmpSeededCCIDs

	DECLARE	@_ccSeed	int

	IF (SELECT Count(Id) FROM AgrCostCenter) = 0
		SET	@_ccSeed		= 1
	ELSE
		SET	@_ccSeed		= IDENT_CURRENT('AgrCostCenter') + 1
	/*
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	S P O N S O R  S E E D S
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	*/
	IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'tmpSeededSponsorIDs')
		DROP TABLE tmpSeededSponsorIDs

	DECLARE	@_sponsorSeed			int

	IF (SELECT Count(Id) FROM AdmSponsor) = 0
		SET	@_sponsorSeed	= 1
	ELSE
		SET	@_sponsorSeed	= IDENT_CURRENT('AdmSponsor') + 1

	DECLARE	@_sql	varchar(1000)
/*
	C R E A T E  F O L D E R  N U M B E R S
	Get the last folder number created by Insight and create new folder numbers
*/
	declare @NextFolderNumber as int
	declare @fiscalYear as int
	if month(getdate())>9 set @fiscalYear = year(getdate())+1 else set @fiscalYear = year(getdate())

	Select @NextFolderNumber = isNull(right(max(foldernumber),7),0)+1 from agragreement where foldernumber like cast(@FiscalYear as varchar) + 'I%'

	IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'tmpSeededFolderNumbers')
		DROP TABLE tmpSeededFolderNumbers

	SET	@_sql = 'SELECT	IDENTITY(int, ' + CAST(@NextFolderNumber AS varchar) + ', 1) AS FolderID, cast(s.ID as int) as ID 
				 INTO dbo.tmpSeededFolderNumbers 
				 FROM Stg_IE_DemogFeed_ExpiredAgreements s
				 where s.IsNewAgreement=1 and isnull(s.folder_number,'''')='''' and s.IsValid = 1 and s.IsAgreementMaintained = 1'
	EXEC(@_sql)

	IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'tmpSeededFolderNumbers') Begin
		-- NEW Folder numbers
		UPDATE s
		SET folder_number = cast(@FiscalYear as varchar) + 'I' + right('000000' + cast(t.FolderID as varchar),7)
		FROM tmpSeededFolderNumbers t
		inner join Stg_IE_DemogFeed_ExpiredAgreements s on s.ID = t.ID

		DROP TABLE dbo.tmpSeededFolderNumbers
	End

	-- now get distinct new folder numbers
	SELECT	DISTINCT folder_number as FolderNumber
	INTO		#NewFolderNumbers
	FROM		Stg_IE_DemogFeed_ExpiredAgreements
	WHERE		FwkResourceId IS NULL and IsNull(ltrim(rtrim(folder_number)),'')<>'' and IsAgreementMaintained = 1 
	ORDER BY	FolderNumber

	IF EXISTS(SELECT 1 FROM tempdb..sysobjects WHERE NAME like '#NewFolderNumbers%') begin

		SET	@_sql = 'SELECT	IDENTITY(int, ' + CAST(@_resourceSeed AS varchar) + ', 1) AS FwkId, FolderNumber INTO dbo.tmpSeededFwkIDs FROM #NewFolderNumbers'
		EXEC(@_sql)

		UPDATE	Stg_IE_DemogFeed_ExpiredAgreements
		SET		FwkResourceId = tmpSeededFwkIDs.FwkId
		FROM	tmpSeededFwkIDs
		WHERE	Stg_IE_DemogFeed_ExpiredAgreements.folder_number = tmpSeededFwkIDs.FolderNumber

		DROP TABLE tmpSeededFwkIDs

		-- AgrBudgetContainerId
		SET	@_sql = 'SELECT	IDENTITY(int, ' + CAST(@_budgetContainerSeed AS varchar) + ', 1) AS BgtId, FolderNumber INTO dbo.tmpSeededBgtIDs FROM #NewFolderNumbers'
		EXEC(@_sql)

		UPDATE	Stg_IE_DemogFeed_ExpiredAgreements
		SET		AgrBudgetContainerId = tmpSeededBgtIDs.BgtId
		FROM	tmpSeededBgtIDs
		WHERE	Stg_IE_DemogFeed_ExpiredAgreements.folder_number = tmpSeededBgtIDs.FolderNumber

		DROP TABLE tmpSeededBgtIDs

		-- AnnAnnotationContainerId
		SET	@_sql = 'SELECT	IDENTITY(int, ' + CAST(@_annotationSeed AS varchar) + ', 1) AS AnnId, FolderNumber INTO dbo.tmpSeededAnnIDs FROM #NewFolderNumbers'
		EXEC(@_sql)

		UPDATE	Stg_IE_DemogFeed_ExpiredAgreements
		SET		AnnAnnotationContainerId = tmpSeededAnnIDs.AnnId
		FROM	tmpSeededAnnIDs
		WHERE	Stg_IE_DemogFeed_ExpiredAgreements.folder_number = tmpSeededAnnIDs.FolderNumber
	
		DROP TABLE tmpSeededAnnIDs


		-- AgrAgreementId
		SET	@_sql = 'SELECT	IDENTITY(int, ' + CAST(@_agreementSeed AS varchar) + ', 1) AS AgrId, FolderNumber INTO dbo.tmpSeededAgrIDs FROM #NewFolderNumbers'
		EXEC(@_sql)

		UPDATE	Stg_IE_DemogFeed_ExpiredAgreements
		SET		AgrAgreementId = tmpSeededAgrIDs.AgrId
		FROM	tmpSeededAgrIDs
		WHERE	Stg_IE_DemogFeed_ExpiredAgreements.folder_number = tmpSeededAgrIDs.FolderNumber

		UPDATE	fm
		SET		AgrAgreementId = coalesce(s.agragreementid,null)
		FROM	Stg_Rex_ExpiredAgreement_FundMap fm
		left outer join tmpSeededAgrIDs tmp on	fm.foldernumber = left(tmp.FolderNumber,11)
		inner join Stg_IE_DemogFeed_ExpiredAgreements s on s.project_grant = fm.fundnumber
		where tmp.foldernumber is null

		UPDATE	Stg_Rex_ExpiredAgreement_FundMap
		SET		AgrAgreementId = tmpSeededAgrIDs.AgrId
		FROM	tmpSeededAgrIDs
		WHERE	Stg_Rex_ExpiredAgreement_FundMap.foldernumber = left(tmpSeededAgrIDs.FolderNumber,11)

		DROP TABLE tmpSeededAgrIDs

		-- SvcEntityId	
		SET	@_sql = 'SELECT	IDENTITY(int, ' + CAST(@_entitySeed AS varchar) + ', 1) AS SvcId, FolderNumber INTO dbo.tmpSeededSvcIDs FROM #NewFolderNumbers'
		EXEC(@_sql)

		UPDATE	Stg_IE_DemogFeed_ExpiredAgreements
		SET		SvcEntityId = tmpSeededSvcIDs.SvcId
		FROM	tmpSeededSvcIDs
		WHERE	Stg_IE_DemogFeed_ExpiredAgreements.folder_number = tmpSeededSvcIDs.FolderNumber

		UPDATE	Stg_Rex_ExpiredAgreement_FundMap
		SET		SvcEntityId = tmpSeededSvcIDs.SvcId
		FROM	tmpSeededSvcIDs
		WHERE	Stg_Rex_ExpiredAgreement_FundMap.foldernumber = left(tmpSeededSvcIDs.FolderNumber,11)

		UPDATE	fm
		SET		SvcEntityId = coalesce(s.SvcEntityId,null)
		FROM	Stg_Rex_ExpiredAgreement_FundMap fm
		left outer join tmpSeededSvcIDs tmp on fm.foldernumber = left(tmp.FolderNumber,11)
		inner join Stg_IE_DemogFeed_ExpiredAgreements s on s.project_grant = fm.fundnumber
		where tmp.foldernumber is null

		-- get the next service entity ID seed to be used in creation of funds.

		select @_entitySeed = coalesce((select max(tmpSeededSvcIDs.SvcId)+1 from tmpSeededSvcIDs),@_entitySeed)

		DROP TABLE tmpSeededSvcIDs
		DROP TABLE #NewFolderNumbers

	End

	-- SvcEntityId for FUNDS
	SET	@_sql = 'SELECT	IDENTITY(int, ' + CAST(@_entitySeed AS varchar) + ', 1) AS SvcId, cast(ID as int) as ID INTO dbo.tmpSeededFundSvcIDs FROM Stg_IE_DemogFeed_ExpiredAgreements where IsNewFund=1 and IsValid = 1'
	EXEC(@_sql)

	IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'tmpSeededFundSvcIDs') Begin
		UPDATE	Stg_IE_DemogFeed_ExpiredAgreements
		SET		AgrFundSvcEntityId = tmpSeededFundSvcIDs.SvcId
		FROM	tmpSeededFundSvcIDs
		WHERE	Stg_IE_DemogFeed_ExpiredAgreements.ID = tmpSeededFundSvcIDs.ID

		DROP TABLE tmpSeededFundSvcIDs
	End

	-- AgrCostCenter.Id for only those that are not defined.
	SET	@_sql = 'SELECT	IDENTITY(int, ' + CAST(@_ccSeed AS varchar) + ', 1) AS MapId, cast(ID as int) as ID INTO dbo.tmpSeededCCIDs FROM Stg_IE_DemogFeed_ExpiredAgreements where IsNewCostCenter = 1 and IsValid = 1'
	EXEC(@_sql)

	IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'tmpSeededCCIDs') Begin
		UPDATE	Stg_IE_DemogFeed_ExpiredAgreements
		SET		AgrCostCenterId = tmpSeededCCIDs.MapId
		FROM	tmpSeededCCIDs
		WHERE	Stg_IE_DemogFeed_ExpiredAgreements.ID		= tmpSeededCCIDs.ID

		DROP TABLE tmpSeededCCIDs
	End

/*
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	F U N D  M A P P I N G
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*/
	-- Insert fund subtype if none exists.
	INSERT INTO AgrFundSubType (Name,Description,FundNumberPrefix,FundTypeId)
	SELECT	'Research Grant ' + SUBSTRING(Stg_IE_DemogFeed_ExpiredAgreements.project_grant,1,1),
			'Research Grant ' + SUBSTRING(Stg_IE_DemogFeed_ExpiredAgreements.project_grant,1,1),
			SUBSTRING(Stg_IE_DemogFeed_ExpiredAgreements.project_grant,1,1),
			1
	FROM	Stg_IE_DemogFeed_ExpiredAgreements
	WHERE	NOT EXISTS
			(
				SELECT	1 FROM AgrFundSubType 
				WHERE	AgrFundSubType.FundTypeId = 1
				AND	(	AgrFundSubType.FundNumberPrefix = SUBSTRING(Stg_IE_DemogFeed_ExpiredAgreements.project_grant,1,3)
				OR		AgrFundSubType.FundNumberPrefix = SUBSTRING(Stg_IE_DemogFeed_ExpiredAgreements.project_grant,1,2)
				OR		AgrFundSubType.FundNumberPrefix = SUBSTRING(Stg_IE_DemogFeed_ExpiredAgreements.project_grant,1,1)	)
			)

	-- get IDs for all the FKs
	-- fund sub-type Id
	UPDATE		Stg_IE_DemogFeed_ExpiredAgreements
	SET			AgrFundSubTypeId = AgrFundSubType.Id
	FROM		AgrFundSubType
	WHERE		AgrFundSubType.FundTypeId = 1
	AND			SUBSTRING(Stg_IE_DemogFeed_ExpiredAgreements.project_grant,1,3) = AgrFundSubType.FundNumberPrefix

	UPDATE		Stg_IE_DemogFeed_ExpiredAgreements
	SET			AgrFundSubTypeId = AgrFundSubType.Id
	FROM		AgrFundSubType
	WHERE		AgrFundSubType.FundTypeId = 1
	AND			SUBSTRING(Stg_IE_DemogFeed_ExpiredAgreements.project_grant,1,2) = AgrFundSubType.FundNumberPrefix
	AND			Stg_IE_DemogFeed_ExpiredAgreements.AgrFundSubTypeId IS NULL

	UPDATE		Stg_IE_DemogFeed_ExpiredAgreements
	SET			AgrFundSubTypeId = AgrFundSubType.Id
	FROM		AgrFundSubType
	WHERE		AgrFundSubType.FundTypeId = 1
	AND			SUBSTRING(Stg_IE_DemogFeed_ExpiredAgreements.project_grant,1,1) = AgrFundSubType.FundNumberPrefix
	AND			Stg_IE_DemogFeed_ExpiredAgreements.AgrFundSubTypeId IS NULL

	/*
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	S E E D  F U N D S
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	*/
	-- AgrFund.Id
	SET	@_sql = 'SELECT	IDENTITY(int, ' + CAST(@_fundSeed AS varchar) + ', 1) AS MapId, cast(ID as int) as ID INTO dbo.tmpSeededFundIDs FROM Stg_IE_DemogFeed_ExpiredAgreements where AgrFundId is null and isnull(project_grant,'''')<> '''' and IsValid = 1'
	EXEC(@_sql)

	IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'tmpSeededFundIDs') Begin
		UPDATE	Stg_IE_DemogFeed_ExpiredAgreements
		SET		AgrFundId = tmpSeededFundIDs.MapId
		FROM	tmpSeededFundIDs
		WHERE	Stg_IE_DemogFeed_ExpiredAgreements.ID = tmpSeededFundIDs.ID

		DROP TABLE tmpSeededFundIDs
	End

	/*
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	S E E D  A G R E E M E N T  F U N D  M A P S
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	*/
	-- AgrFund_AgrAgreement_Map.Id
	SET	@_sql = 'SELECT	IDENTITY(int, ' + CAST(@_fundAgreeMapSeed AS varchar) + ', 1) AS MapId, cast(s.ID as int) as ID INTO dbo.tmpSeededFundAgreeMapIDs FROM Stg_Rex_ExpiredAgreement_FundMap s'
	EXEC(@_sql)

	IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'tmpSeededFundAgreeMapIDs') Begin

		UPDATE	bh
		SET		AgrFundAgreeMapId = tmp.MapId
		FROM	Stg_Rex_ExpiredAgreement_BudgetHeader bh
		inner join tmpSeededFundAgreeMapIDs tmp ON	bh.AgrFundAgreeMapId = tmp.ID

		UPDATE	bh
		SET		AgrFundAgreeMapId = null
		FROM	Stg_Rex_ExpiredAgreement_BudgetHeader bh
		left outer join tmpSeededFundAgreeMapIDs tmp on bh.AgrFundAgreeMapId = tmp.MapId
		WHERE	tmp.mapId is null

		UPDATE	Stg_Rex_ExpiredAgreement_FundMap
		SET		ID = tmpSeededFundAgreeMapIDs.MapId
		FROM	tmpSeededFundAgreeMapIDs
		WHERE	Stg_Rex_ExpiredAgreement_FundMap.ID = tmpSeededFundAgreeMapIDs.ID

		UPDATE	fm
		SET		ID = null
		FROM	Stg_Rex_ExpiredAgreement_FundMap fm
		left outer join tmpSeededFundAgreeMapIDs tmp on	fm.ID = tmp.MapId
		where tmp.MapId is null

		UPDATE	Stg_Rex_ExpiredAgreement_CostCenterFundMap
		SET		AgrFundAgreementMapID = tmpSeededFundAgreeMapIDs.MapId
		FROM	tmpSeededFundAgreeMapIDs
		WHERE	Stg_Rex_ExpiredAgreement_CostCenterFundMap.ID = tmpSeededFundAgreeMapIDs.ID

		UPDATE	fm
		SET		AgrFundAgreementMapID = null
		FROM	Stg_Rex_ExpiredAgreement_CostCenterFundMap fm
		left outer join tmpSeededFundAgreeMapIDs tmp on	fm.ID = tmp.MapId
		where tmp.MapId is null

		DROP TABLE tmpSeededFundAgreeMapIDs
	End
	/*
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	S E E D  S P O N S O R S
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	*/

	-- now get distinct new sponsor numbers
	SELECT	DISTINCT sponsor_name as sponsorName,sponsor_code_id as SponsorCode
	INTO		#tmp2
	FROM		Stg_IE_DemogFeed_ExpiredAgreements
	WHERE		IsNewSponsor = 1 and IsValid = 1 and isnull(sponsor_name,'')<> '' and admSponsorId is null
	ORDER BY	sponsor_name,sponsor_code_id

	IF EXISTS(SELECT 1 FROM tempdb..sysobjects WHERE NAME like '#tmp2%') begin
		-- AdmSponsor.Id
		SET	@_sql = 'SELECT	IDENTITY(int, ' + CAST(@_sponsorSeed AS varchar) + ', 1) AS MapId, SponsorName, SponsorCode  INTO dbo.tmpSeededSponsorIDs FROM #TMP2'
		EXEC(@_sql)

		Drop Table #tmp2

		IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'tmpSeededSponsorIDs') Begin
			UPDATE	Stg_IE_DemogFeed_ExpiredAgreements
			SET		AdmSponsorId = tmpSeededSponsorIDs.MapId
			FROM	tmpSeededSponsorIDs
			WHERE	Stg_IE_DemogFeed_ExpiredAgreements.Sponsor_Name = tmpSeededSponsorIDs.SponsorName
				and Stg_IE_DemogFeed_ExpiredAgreements.Sponsor_Code_id = tmpSeededSponsorIDs.sponsorCode

			DROP TABLE tmpSeededSponsorIDs
		End
	End

	/*
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	I D E N T I F Y  C U R R E N T  F U N D S
	Identify and flag the current fund for each agreement.  The current fund is
	the fund that has the latest budget start date.
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	*/
	UPDATE s set IsCurrentFund = 1
	From Stg_IE_DemogFeed_ExpiredAgreements s
	Where	s.id = (select max(s1.id) from Stg_IE_DemogFeed_ExpiredAgreements s1 
					where s.Folder_number = s1.Folder_number
						AND IsNull(s1.dtbudgetStart,'') = (select max(IsNull(s2.dtbudgetStart,'')) 
															from Stg_IE_DemogFeed_ExpiredAgreements s2
															where s1.Folder_number = s2.Folder_number
																))
	/*
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	S E E D  B U D G E T  C O N T A I N E R  V I E W
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	*/
	-- AgrFund_AgrAgreement_Map.Id
	SET	@_sql = 'SELECT	IDENTITY(int, ' + CAST(@_budgetContainerViewSeed AS varchar) + ', 2) AS MapId, cast(s.ID as int) as ID INTO dbo.tmpSeededBudgetContainerViewIDs FROM Stg_IE_DemogFeed_ExpiredAgreements s where s.AgrBudgetContainerViewId is null AND s.AgrBudgetContainerId is not null and s.IsCurrentFund= 1'
	EXEC(@_sql)

	IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'tmpSeededBudgetContainerViewIDs') Begin
		UPDATE	Stg_IE_DemogFeed_ExpiredAgreements
		SET		AgrBudgetContainerViewId = tmpSeededBudgetContainerViewIDs.MapId
				,AgrBudgetContainerViewId1 = tmpSeededBudgetContainerViewIDs.MapId + 1
		FROM	tmpSeededBudgetContainerViewIDs
		WHERE	Stg_IE_DemogFeed_ExpiredAgreements.ID = tmpSeededBudgetContainerViewIDs.ID

		DROP TABLE tmpSeededBudgetContainerViewIDs
	End
	/*
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	S E E D  B U D G E T S
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	*/
	-- AgrFund_AgrAgreement_Map.Id
	SET	@_sql = 'SELECT	IDENTITY(int, ' + CAST(@_budgetSeed AS varchar) + ', 1) AS MapId, cast(s.ID as int) as ID INTO dbo.tmpSeededBudgetIDs FROM stg_rex_expiredAgreement_BudgetHeader s'
	EXEC(@_sql)

	IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'tmpSeededBudgetIDs') Begin
		UPDATE	stg_rex_expiredAgreement_BudgetItem
		SET		AgrBudgetId = tmpSeededBudgetIDs.MapId
		FROM	tmpSeededBudgetIDs
		WHERE	stg_rex_expiredAgreement_BudgetItem.AgrBudgetId = tmpSeededBudgetIDs.ID

		UPDATE	bi
		SET		AgrBudgetId = null
		FROM	stg_rex_expiredAgreement_BudgetItem bi
		left outer join tmpSeededBudgetIDs tmp on	bi.AgrBudgetId = tmp.MapId
		Where tmp.MapId is null

		UPDATE	stg_rex_expiredAgreement_BudgetICRate
		SET		AgrBudgetId = tmpSeededBudgetIDs.MapId
		FROM	tmpSeededBudgetIDs
		WHERE	stg_rex_expiredAgreement_BudgetICRate.AgrBudgetId = tmpSeededBudgetIDs.ID

		UPDATE	bic
		SET		AgrBudgetId = null
		FROM	stg_rex_expiredAgreement_BudgetICRate bic
		left outer join tmpSeededBudgetIDs tmp on bic.AgrBudgetId = tmp.MapId
		Where tmp.MapId is null

		UPDATE	stg_rex_expiredAgreement_BudgetHeader
		SET		Id = tmpSeededBudgetIDs.MapId
		FROM	tmpSeededBudgetIDs
		WHERE	stg_rex_expiredAgreement_BudgetHeader.ID = tmpSeededBudgetIDs.ID

		DROP TABLE tmpSeededBudgetIDs
	End

/*
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	D E T E R M I N E  C H A N G E S
	Changes come in the form of a new Id value for most data in this feed.  There are
	a small number of individual data items that also get updated that must be checked
	to see if they changed.
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*/
	UPDATE s set IsChanged = 1
	From Stg_IE_DemogFeed_ExpiredAgreements s
	left outer join agragreement aa on aa.id = s.agragreementid
	left outer join AgrFund_agragreement_map afam on afam.agragreementid = s.agragreementid and afam.agrfundid = s.agrfundid
	left outer join SvcEntity_AdmSponsor_Map asm on asm.svcentityid = s.svcentityid and asm.AdmSponsorRelationTypeId = 1
	WHERE
		-- Agreement Changes
		((IsNull(s.Orig_AgrTransactionTypeId,0) <> IsNull(s.AgrTransactionTypeId,0)
		or IsNull(s.Orig_AgrAgreementTypeId,0) <>  IsNull(s.AgrAgreementTypeId,0)
		or IsNull(s.Orig_AgrAgreementStatusTypeId,0) <>  IsNull(s.AgrAgreementStatusTypeId,0)
		or IsNull(s.Orig_PI_AdmPersonID,0) <>  IsNull(s.PI_AdmPersonID,0)
		or IsNull(s.Orig_AdmSponsorId,0) <>  IsNull(s.AdmSponsorId,0)
		or IsNull(s.Orig_fwkDomainOrganizationId,0) <>  IsNull(s.fwkDomainOrganizationId,0)
		or IsNull(s.Orig_finICBaseTypeId,0) <> IsNull(s.finICBaseTypeId,0)
		or IsNull(s.Orig_AgrActivityTypeId,0) <>  IsNull(s.AgrActivityTypeId,0)
		or IsNull(s.Orig_FinAccountCycleTypeId,0) <> IsNull(s.FinAccountCycleTypeId,0)
		or IsNull(s.Orig_admfacilityId,0) <> IsNull(s.AdmFacilityId,0)
	 		-- INDIVIDUAL column change checking below


		or left(convert(varchar,lower(IsNull(aa.ShortTitle,''))),30) <> lower(IsNull(s.description,''))


		or IsNull(aa.ProjectStartDate,'') <> IsNull(s.dtProjectStart,'')


		or IsNull(aa.ProjectEndDate,'') <> IsNull(s.dtProjectEnd,'')


		or IsNull(asm.SponsorNumber,'') <> IsNull(s.sponsor_agree_id_format,''))


		and IsNull(s.IsCurrentFund,0) = 1)





		or 


		--Fund Changes 


		IsNull(s.Orig_AgrFundStatusTypeId,0) <> IsNull(s.AgrFundStatusTypeId,0)
		or IsNull(s.Orig_AgrFundAwardTypeId,0) <> IsNull(s.AgrFundAwardTypeId,0)
		or IsNull(s.Orig_AgrFundOverheadClassificationId,0) <> IsNull(s.AgrFundOverheadClassificationId,0)
		or IsNull(s.Orig_AgrFundTypeId,0) <> IsNull(s.AgrFundTypeId,0)
		or IsNull(s.Orig_AgrFundSubTypeId,0) <> IsNull(s.AgrFundSubTypeId,0)
		or (((select cc.Number from AgrCostCenter cc where cc.Id =IsNull(s.Orig_AgrCostCenterId,0)) <> IsNull(s.Cost_Center,'')
		or IsNull(s.Orig_AgrCostCenterStatusTypeId,0) <> IsNull(s.AgrCostCenterStatusTypeId,0)) and IsNull(resp_inst,'') = 'BWH')
	 		-- INDIVIDUAL column change checking below


		or IsNull(afam.CFDA,'') <> IsNull(s.cfda_number,'')


		or IsNull(afam.DocumentLetter,'') <> IsNull(s.doc_letter,'')


		or left(lower(IsNull(afam.FundShortTitle,'')),30) <> lower(IsNull(s.Description,''))


		or lower(IsNull(afam.FundTitle,'')) <> left(lower(IsNull(s.long_Description,'')),128)

	/*
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	Create a table of all the folder numbers sorted in the order of the new agreement
	report
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	*/
	select identity(int,1,1) as Id,cast(s.id as int) as stagingId,s.folder_number
		, cast('' as varchar(12)) as PreviousFolderNumber
	into #PreviousFolder 
	from Stg_IE_DemogFeed_ExpiredAgreements s 
	where s.Isvalid = 1
	order by s.folder_number, s.dtbudgetstart, CAST(s.Id AS INT)

	/*
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	Update the previous folder number column that goes with the folder number.
	This will be used to break on folder numbers in the report.
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	*/
	update t 
	set PreviousFolderNumber = IsNull((select t1.folder_number 
								 from #PreviousFolder t1 where t1.Id = (t.id-1)),'')
	from #PreviousFolder t 

	/*
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	Create the Report output including the previous folder number.
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	*/
	update s
	Set  PreviousFolderNumber = pf.PreviousFolderNumber 
	from Stg_IE_DemogFeed_ExpiredAgreements s
	inner join #PreviousFolder pf on pf.StagingId = s.Id

	drop table #PreviousFolder

	/*
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	Check for bad PI person ID.  If bad, re-map from recomabstract
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	*/
	update s
	set PIPersonId = mh.newpersonid
	from Stg_Rex_ExpiredAgreements s
	left outer join personmergehistory mh on mh.oldpersonid = s.PIPersonId
	left outer join admPerson ap on s.PIPersonId = ap.id
	where ap.Id is null

	/*
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	Check for bad Staff person ID.  If bad, re-map from recomabstract
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	*/
	update s
	set AdmPersonId = mh.newpersonid
	from Stg_Rex_ExpiredAgreement_StaffedPersonMap s
	inner join personmergehistory mh on mh.oldpersonid = s.AdmPersonId
	left outer join admPerson ap on s.AdmPersonId = ap.id
	where ap.Id is null

	/*
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	Check for bad Manager person ID.  If bad, re-map from recomabstract
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	*/
	update s
	set ManagerId = mh.newpersonid
	from Stg_Rex_ExpiredAgreement_FundMap s
	inner join personmergehistory mh on mh.oldpersonid = s.ManagerId
	left outer join admPerson ap on s.ManagerId = ap.id
	where ap.Id is null

	/*
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	D E T E C T  E R R O R S
	Look for stuff that does not map
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	*/
	UPDATE	Stg_IE_DemogFeed_ExpiredAgreements
	SET		IsValid = 0
	Where	IsValid = 1 and
		   (isNull(AgrFundId,0)=0 
		or isNull(AgrAgreementId,0)=0 
		or isNull(SvcEntityId,0)=0 
		or isNull(FwkResourceId,0)=0 
		--or isNull(AgrFundAgreementMapId,0)=0 
		or (isNull(AgrBudgetContainerId,0)=0 
		AND isNull(AgrBudgetContainerViewId,0)<>0))

	SET NOCOUNT OFF

END




GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Creating [dbo].[GetProjectHeader]'
GO

create procedure [dbo].[GetProjectHeader]
(
	@fundNumber	Varchar(30), 
	@resourceId	int,
	@budgetYear	int	= NULL
)
as
begin
	set nocount on

	set @budgetYear = isnull(@budgetYear, 0)

	if (@fundNumber = '&nbsp;') set @fundNumber=''

	if isnull(@fundNumber,'') <> ''
		begin
			select top 1 drv.* from
			(select distinct
				agf.FundNumber as FundNumber,
				isnull(agf.PILastName,'') + ', ' + isnull(agf.PIFirstName,'') as PIName,
				isnull(aa.ShortTitle,'') as ProjectName,
				agf.SponsorName as SponsorName,
				agf.SponsorNumber as SponsorId,
				coalesce(abf.BudgetStartDate,agf.BudgetStartDate,'') as BudgetStart,
				coalesce(abf.BudgetEndDate,agf.BudgetEndDate,'') as BudgetEnd,
				isnull(agf.ProjectStartDate,'') as ProjectStart,
				isnull(agf.ProjectEndDate,'') as ProjectEnd,
				CASE isnull(fst.Name, 'R')
					WHEN 'A' THEN 'Active'
					WHEN 'I' THEN 'Inactive'
					WHEN 'R' THEN 'Pending'
				END AS FundStatus

			from dbo.AgrAgreement_Fct agf
			inner join dbo.AgrAgreement aa on aa.Id = agf.AgreementId
			left outer join dbo.AgrBudget_Fct abf on agf.FundId = abf.FundId
			and
				isnull(abf.BudgetViewTypeId, 3) = 
					isnull(
					(
						select	max(abf2.BudgetViewTypeId)
						from	dbo.AgrBudget_Fct abf2
						where	abf2.FundId = agf.FundId and abf2.BudgetViewTypeId <> 6
					),3)
			and
				isnull(abf.BudgetStartDate,'') =
				CASE
					WHEN 
						IsNull((
							select	isnull(max(abf2.BudgetStartDate),'')
							from	dbo.AgrBudget_Fct abf2
							where	abf2.FundId = agf.FundId
							and		((abf2.BudgetViewTypeId = isnull(abf.BudgetViewTypeId, 3) and agf.StatusTypeId <> 1) or
										(abf2.BudgetViewTypeId = 1 and agf.StatusTypeId = 1))
							
						),'') = '' THEN ''
				ELSE
				CASE
					WHEN @budgetYear = 0 THEN
						IsNull((
							select	max(isnull(abf3.BudgetStartDate,''))
							from	dbo.AgrBudget_Fct abf3
							where	abf3.FundId = agf.FundId
							and		((abf3.BudgetViewTypeId = isnull(abf.BudgetViewTypeId, 3) and agf.StatusTypeId <> 1) or
										(abf3.BudgetViewTypeId = 1 and agf.StatusTypeId = 1))
						),'')
					ELSE	
						IsNull((
							select	max(isnull(abf4.BudgetStartDate,''))
							from	dbo.AgrBudget_Fct abf4
							where	abf4.FundId = agf.FundId
							and		year(abf4.BudgetStartDate) = @budgetYear
							and		((abf4.BudgetViewTypeId = isnull(abf.BudgetViewTypeId, 3) and agf.StatusTypeId <> 1) or
										(abf4.BudgetViewTypeId = 1 and agf.StatusTypeId = 1))
						),'')
					END
				END
			left outer join dbo.AgrFundStatusType fst on agf.FundStatusTypeId = fst.Id
			where
				agf.FundNumber = @fundNumber) drv

		end
	else if isnull(@resourceId,-1) <> -1
		begin
			select top 1 drv.* from
			(select distinct
				isnull(agf.FundNumber,'N/A') as FundNumber,
				isnull(agf.PILastName,'') + ', ' + isnull(agf.PIFirstName,'') as PIName,
				isnull(aa.ShortTitle,'') as ProjectName,
				agf.SponsorName as SponsorName,
				agf.SponsorNumber as SponsorId,
				coalesce(abf.BudgetStartDate,agf.BudgetStartDate,'') as BudgetStart,
				coalesce(abf.BudgetEndDate,agf.BudgetEndDate,'') as BudgetEnd,
				isnull(agf.ProjectStartDate,'') as ProjectStart,
				isnull(agf.ProjectEndDate,'') as ProjectEnd,
				CASE isnull(fst.Name, 'R')
					WHEN 'A' THEN 'Active'
					WHEN 'I' THEN 'Inactive'
					WHEN 'R' THEN 'Pending'
				END AS FundStatus

			from dbo.AgrAgreement_Fct agf
			inner join dbo.AgrAgreement aa on aa.Id = agf.AgreementId
			left outer join AgrBudget_Fct abf on agf.FundId = abf.FundId
			and
				isnull(abf.BudgetViewTypeId, 3) = 
					isnull(
					(
						select	max(abf2.BudgetViewTypeId)
						from	dbo.AgrBudget_Fct abf2
						where	abf2.FundId = agf.FundId
					),3)
			and
				isnull(abf.BudgetStartDate,'') =
				CASE
					WHEN 
						(
							select	isnull(max(abf2.BudgetStartDate),'')
							from	dbo.AgrBudget_Fct abf2
							where	abf2.FundId = agf.FundId
							and		((abf2.BudgetViewTypeId = isnull(abf.BudgetViewTypeId, 3) and agf.StatusTypeId <> 1) or
										(abf2.BudgetViewTypeId = 1 and agf.StatusTypeId = 1))
						) = '' THEN ''
				ELSE
				CASE
					WHEN @budgetYear = 0 THEN
						(
							select	max(isnull(abf2.BudgetStartDate,''))
							from	dbo.AgrBudget_Fct abf2
							where	abf2.FundId = agf.FundId
							and		((abf2.BudgetViewTypeId = isnull(abf.BudgetViewTypeId, 3) and agf.StatusTypeId <> 1) or
										(abf2.BudgetViewTypeId = 1 and agf.StatusTypeId = 1))
						)
					ELSE
								
						IsNull((
							select	max(isnull(abf4.BudgetStartDate,''))
							from	dbo.AgrBudget_Fct abf4
							where	abf4.FundId = agf.FundId
							and		year(abf4.BudgetStartDate) = @budgetYear
							and		((abf4.BudgetViewTypeId = isnull(abf.BudgetViewTypeId, 3) and agf.StatusTypeId <> 1) or
										(abf4.BudgetViewTypeId = 1 and agf.StatusTypeId = 1))
						),'')
					END
				END
			left outer join dbo.AgrFundStatusType fst on agf.FundStatusTypeId = fst.Id

			where
				@resourceId = agf.ResourceId) drv
		end
end

GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Altering [dbo].[GetClinicalTrialBudgetTotals]'
GO
SET ANSI_NULLS OFF
GO

ALTER PROCEDURE dbo.GetClinicalTrialBudgetTotals (@budgetId int) AS
BEGIN
    SET NOCOUNT ON

    DECLARE @overheadRate decimal(4,2), @overheadRateCode varchar(256), @institutionCode varchar(256)
    SELECT @institutionCode = InstitutionCode, @overheadRateCode = OverheadRateCode FROM ClinicalTrialBudget WHERE Id = @budgetId
    IF @overheadRateCode = 'ClinicalTrialBudgetOverheadRateOther'
    BEGIN
        SELECT @overheadRate = OtherNegotiatedRate / 100 FROM ClinicalTrialBudget WHERE Id = @budgetId
    END
    ELSE
    BEGIN
        SELECT @overheadRate = CAST (a.Value AS DECIMAL(4,2)) / 100 FROM RefCodeAttribute a WHERE a.RefCode = @overheadRateCode AND a.RefDomain='ClinicalTrialBudgetOverheadRate'
    END

    SELECT 'Tasks - ' + CASE WHEN s.StudyStaffRoleCode = 'ClinicalTrialBudgetStaffRoleOther' THEN s.OtherRoleText ELSE r.refmeaning END Role, 
        ISNULL( SUM( t.taskcost ), 0 ) TotalPerSubject,
        ISNULL( SUM( CAST ( (t.taskcost * (CASE WHEN t.applyoverhead = 1 THEN 1 + @overheadRate ELSE 1 END)) AS DECIMAL(16,2) ) ), 0 ) TotalPerSubjectWithOverhead,
        ISNULL( SUM( CAST ( (t.taskcost * b.enrolledsubjects) AS DECIMAL(16,2)) ), 0 ) Total,
        ISNULL( SUM( CAST ( (t.taskcost * b.enrolledsubjects * (CASE WHEN t.applyoverhead = 1 THEN 1 + @overheadRate ELSE 1 END)) AS DECIMAL(16,2) ) ), 0 ) TotalWithOverhead
    FROM clinicaltrialbudget b, clinicaltrialbudgettask t, clinicaltrialbudgetstaff s, refcode r, clinicaltrialbudgetmilestonevisit bmv
        WHERE b.Id = @budgetId
            AND t.clinicaltrialbudgetid = b.id
            AND s.id = t.clinicaltrialbudgetstaffid
            AND r.refdomain = 'ClinicalTrialBudgetStaffRole'
            AND r.refcode = s.studystaffrolecode
            AND bmv.relateclass = 'BudgetTask'
            AND bmv.relateid = t.id
            AND bmv.required = 1
            AND bmv.standardofcare = 0
        GROUP BY t.clinicaltrialbudgetstaffid, s.StudyStaffRoleCode, r.refmeaning, s.OtherRoleText

    SELECT 'Tasks - Total' Role,
        ISNULL( SUM( t.taskcost ), 0 ) TotalPerSubject,
        ISNULL( SUM( CAST ( (t.taskcost * (CASE WHEN t.applyoverhead = 1 THEN 1 + @overheadRate ELSE 1 END)) AS DECIMAL(16,2) ) ), 0 ) TotalPerSubjectWithOverhead,
        ISNULL( SUM( CAST ( (t.taskcost * b.enrolledsubjects) AS DECIMAL(16,2)) ), 0 ) Total,
        ISNULL( SUM( CAST ( (t.taskcost * b.enrolledsubjects * (CASE WHEN t.applyoverhead = 1 THEN 1 + @overheadRate ELSE 1 END)) AS DECIMAL(16,2) ) ), 0 ) TotalWithOverhead
    FROM clinicaltrialbudget b, clinicaltrialbudgettask t, clinicaltrialbudgetstaff s, refcode r, clinicaltrialbudgetmilestonevisit bmv
        WHERE b.Id = @budgetId
            AND t.clinicaltrialbudgetid = b.id
            AND s.id = t.clinicaltrialbudgetstaffid
            AND r.refdomain = 'ClinicalTrialBudgetStaffRole'
            AND r.refcode = s.studystaffrolecode
            AND bmv.relateclass = 'BudgetTask'
            AND bmv.relateid = t.id
            AND bmv.required = 1
            AND bmv.standardofcare = 0

    SELECT'Professional Fees' Role,
        ISNULL( SUM( CAST ( (p.professionalfee) AS DECIMAL(16,2) ) ), 0 ) TotalPerSubject,
        ISNULL( SUM( CAST ( (p.professionalfee * (CASE WHEN p.applyoverhead = 1 THEN 1 + @overheadRate ELSE 1 END)) AS DECIMAL(16,2) ) ), 0 ) TotalPerSubjectWithOverhead,
        ISNULL( SUM( CAST ( (p.professionalfee * b.enrolledsubjects) AS DECIMAL(16,2) ) ), 0 ) Total,
        ISNULL( SUM( CAST ( (p.professionalfee * b.enrolledsubjects * (CASE WHEN p.applyoverhead = 1 THEN 1 + @overheadRate ELSE 1 END)) AS DECIMAL(16,2) ) ), 0 ) TotalWithOverhead
    FROM clinicaltrialbudget b, clinicaltrialbudgetprocedure p, clinicaltrialbudgetmilestonevisit bmv
    WHERE b.id = @budgetId
        AND p.clinicaltrialbudgetid = b.id
        AND bmv.relateclass = 'BudgetProcedure'
        AND bmv.relateid = p.id
        AND bmv.required = 1
        AND bmv.standardofcare = 0

    IF (@institutionCode = 'ClinicalTrialBudgetInstitutionBWH')
        BEGIN
        SELECT
            'Inpatient Procedures' Role,
            ISNULL( SUM( CAST ( (p.procedurecost) AS DECIMAL(16,2) ) ), 0 ) TotalPerSubject,
            ISNULL( SUM( CAST ( (p.procedurecost * (CASE when p.applyoverhead = 1 THEN 1 + @overheadRate ELSE 1 END)) AS DECIMAL(16,2) ) ), 0 ) TotalPerSubjectWithOverhead,
            ISNULL( SUM( CAST ( (p.procedurecost * b.enrolledsubjects) AS DECIMAL(16,2) ) ), 0 ) Total,
            ISNULL( SUM( CAST ( (p.procedurecost * b.enrolledsubjects * (CASE when p.applyoverhead = 1 THEN 1 + @overheadRate ELSE 1 END)) AS DECIMAL(16,2) ) ), 0 ) TotalWithOverhead,
            ISNULL( SUM( CAST ( (p.procedurecost * b.enrolledsubjects) AS DECIMAL(16,2) ) ), 0 ) Actual,
            ISNULL( SUM( CAST ( (b.enrolledsubjects * ISNULL(bcf.Price, 0) * (CASE when p.applyoverhead = 1 THEN 1 + @overheadRate ELSE 1 END)) AS DECIMAL(16,2))), 0) TotalResearchRateWithOverhead
        FROM clinicaltrialbudget b, clinicaltrialbudgetprocedure p, clinicaltrialbudgetmilestonevisit bmv, bwh_cdmfeed bcf
        WHERE b.Id = @budgetId
            AND p.clinicaltrialbudgetid = b.id
            AND p.Inpatient = 1 
            AND bmv.relateclass = 'BudgetProcedure'
            AND bmv.relateid = p.id
            AND bmv.required = 1
            AND bmv.standardofcare = 0
            AND bcf.ChargeCode = p.ProcedureChargeCode

        SELECT
            'Outpatient Procedures' Role,
            ISNULL( SUM( CAST ( (p.procedurecost) AS DECIMAL(16,2) ) ), 0 ) TotalPerSubject,
            ISNULL( SUM( CAST ( (p.procedurecost * (CASE when p.applyoverhead = 1 THEN 1 + @overheadRate ELSE 1 END)) AS DECIMAL(16,2) ) ), 0 ) TotalPerSubjectWithOverhead,
            ISNULL( SUM( CAST ( (p.procedurecost * b.enrolledsubjects) AS DECIMAL(16,2) ) ), 0 ) Total,
            ISNULL( SUM( CAST ( (p.procedurecost * b.enrolledsubjects * (CASE when p.applyoverhead = 1 THEN 1 + @overheadRate ELSE 1 END)) AS DECIMAL(16,2) ) ), 0 ) TotalWithOverhead,
            ISNULL( SUM( CAST ( (p.procedurecost * b.enrolledsubjects) AS DECIMAL(16,2) ) ), 0 ) Actual,
            ISNULL( SUM( CAST ( (b.enrolledsubjects * ISNULL(bcf.Price, 0) * (CASE when p.applyoverhead = 1 THEN 1 + @overheadRate ELSE 1 END)) AS DECIMAL(16,2))), 0) TotalResearchRateWithOverhead
        FROM clinicaltrialbudget b, clinicaltrialbudgetprocedure p, clinicaltrialbudgetmilestonevisit bmv, bwh_cdmfeed bcf
        WHERE b.Id = @budgetId
            AND p.clinicaltrialbudgetid = b.id
            AND p.Inpatient = 0
            AND bmv.relateclass = 'BudgetProcedure'
            AND bmv.relateid = p.id
            AND bmv.required = 1
            AND bmv.standardofcare = 0
            AND bcf.ChargeCode = p.ProcedureChargeCode
        END
    ELSE
        BEGIN
        SELECT
            'Inpatient Procedures' Role,
            ISNULL( SUM( CAST ( (p.procedurecost) AS DECIMAL(16,2) ) ), 0 ) TotalPerSubject,
            ISNULL( SUM( CAST ( (p.procedurecost * (CASE when p.applyoverhead = 1 THEN 1 + @overheadRate ELSE 1 END)) AS DECIMAL(16,2) ) ), 0 ) TotalPerSubjectWithOverhead,
            ISNULL( SUM( CAST ( (p.procedurecost * b.enrolledsubjects) AS DECIMAL(16,2) ) ), 0 ) Total,
            ISNULL( SUM( CAST ( (p.procedurecost * b.enrolledsubjects * (CASE when p.applyoverhead = 1 THEN 1 + @overheadRate ELSE 1 END)) AS DECIMAL(16,2) ) ), 0 ) TotalWithOverhead,
            ISNULL( SUM( CAST ( (p.procedurecost * b.enrolledsubjects) AS DECIMAL(16,2) ) ), 0 ) Actual,
            ISNULL( SUM( CAST ( (b.enrolledsubjects * (CASE WHEN mcf.ResearchRate IS NOT NULL THEN mcf.Price * mcf.ResearchRate/100 ELSE ISNULL(mcf.Price, 0) END) * (CASE when p.applyoverhead = 1 THEN 1 + @overheadRate ELSE 1 END)) AS DECIMAL(16,2))), 0) TotalResearchRateWithOverhead
        FROM clinicaltrialbudget b, clinicaltrialbudgetprocedure p, clinicaltrialbudgetmilestonevisit bmv, mgh_cdmfeed mcf
        WHERE b.Id = @budgetId
            AND p.clinicaltrialbudgetid = b.id
            AND p.Inpatient = 1 
            AND bmv.relateclass = 'BudgetProcedure'
            AND bmv.relateid = p.id
            AND bmv.required = 1
            AND bmv.standardofcare = 0
            AND mcf.ChargeCode = p.ProcedureChargeCode

        SELECT 'Outpatient Procedures' Role,
            ISNULL( SUM( CAST ( (p.procedurecost) AS DECIMAL(16,2) ) ), 0 ) TotalPerSubject,
            ISNULL( SUM( CAST ( (p.procedurecost * (CASE when p.applyoverhead = 1 THEN 1 + @overheadRate ELSE 1 END)) AS DECIMAL(16,2) ) ), 0 ) TotalPerSubjectWithOverhead,
            ISNULL( SUM( CAST ( (p.procedurecost * b.enrolledsubjects) AS DECIMAL(16,2) ) ), 0 ) Total,
            ISNULL( SUM( CAST ( (p.procedurecost * b.enrolledsubjects * (CASE when p.applyoverhead = 1 THEN 1 + @overheadRate ELSE 1 END)) AS DECIMAL(16,2) ) ), 0 ) TotalWithOverhead,
            ISNULL( SUM( CAST ( (p.procedurecost * b.enrolledsubjects) AS DECIMAL(16,2) ) ), 0 ) Actual,
            ISNULL( SUM( CAST ( (b.enrolledsubjects * (CASE WHEN mcf.ResearchRate IS NOT NULL THEN mcf.Price * mcf.ResearchRate/100 ELSE ISNULL(mcf.Price, 0) END) * (CASE when p.applyoverhead = 1 THEN 1 + @overheadRate ELSE 1 END)) AS DECIMAL(16,2))), 0) TotalResearchRateWithOverhead
        FROM clinicaltrialbudget b, clinicaltrialbudgetprocedure p, clinicaltrialbudgetmilestonevisit bmv, mgh_cdmfeed mcf
        WHERE b.Id = @budgetId
        AND p.clinicaltrialbudgetid = b.id
        AND p.Inpatient = 0
        AND bmv.relateclass = 'BudgetProcedure'
        AND bmv.relateid = p.id
        AND bmv.required = 1
        AND bmv.standardofcare = 0
        AND mcf.ChargeCode = p.ProcedureChargeCode
    END

    SELECT 'Other Study Charges' Role, null TotalPerSubject, null TotalPerSubjectWithOverhead, CAST( SUM( expensecost ) AS DECIMAL(16,2) ) Total, CAST( SUM( expensecost * (CASE when e.applyoverhead = 1 THEN 1 + @overheadRate ELSE 1 END)) AS DECIMAL(16,2) ) TotalWithOverhead
    FROM clinicaltrialbudget b, clinicaltrialbudgetexpense e 
    WHERE b.id=@budgetId AND e.clinicaltrialbudgetid = b.id AND e.VariableCost=0

END

GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Altering [dbo].[CleanWorkflowItem]'
GO
SET ANSI_NULLS ON
GO

ALTER PROCEDURE dbo.CleanWorkflowItem
(
	@executionId int,
	@updateStatus int = 1	
)
AS	
	declare @protocolProcessId int
	declare @protocolId int	
	declare @OverallStatusWIP int
	declare @Unlock int

	set @protocolProcessId = (select ProtocolProcessId from ProtocolProcess_Workflow_Map where ExecutionId = @executionId)	
	set @protocolId = (select ProtocolId from ProtocolProcess where Id = @protocolProcessId)
	set @OverallStatusWIP = 10
	set @Unlock = 0

	--Delete Document map and all consent forms created for that protocol
	--Mark it for removal
	update Document
	set MarkForRemoval = 1
	where Id in 
		(select DocumentId
		from 
			Admperson_Protocol_Document_Map m join Document d on
			m.DocumentId = d.Id
			and d.Name = 'consentForm.pdf'
			and m.ProtocolId = @protocolId)

	--Delete Map table entry now
	Delete Admperson_Protocol_Document_Map
	where Id in (
			select m.Id
			from 
				Admperson_Protocol_Document_Map m join Document d on
				m.ProtocolId = @protocolId
				and m.DocumentId = d.Id
				and d.Name = 'consentForm.pdf'
				)

	--Delete it from the mappping table
	delete from ProtocolProcess_Workflow_Map 
	where ExecutionId = @executionId

	--Delete it from Skelta Execution detail table
	delete from SWExecutiondetails 
	where executionid = @executionId

	--Delete it from Skelta execute table
	delete from SWExecute
	where id = @executionId

	if (@updateStatus = 1) 
	begin
		--Update Protocol record
		--Overall status to Work In Progress and unlock it.
		Update Protocol
		set OverallStatusId = @OverallStatusWIP, 
		IsLocked = @Unlock 
		where Id = @protocolId

		--Update ProtocolProcess record	
		update ProtocolProcess
		set Status = 'PPSTATUS_WIP'
		where Id = @protocolProcessId
	end




GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Altering [dbo].[GetCustomReport]'
GO
/******************************************************************                                        
* Name:   [GetCustomReport]                                        
* Purpose:  Retrieves COIIds matching the filter parameters passed in using multiple table joins       
* Note:     The parameters for selected charts only will be passed in with the common search parameters       
   and the sort parameters.      
*********************************************************************/                                        
ALTER PROCEDURE [dbo].[GetCustomReport]                                            
(                                  
@firstName  VARCHAR(64)=null,                                            
@lastName VARCHAR(64)=null,                                            
@userName VARCHAR(36)=null,                                  
@organizationXml Text=null,                           
@nothingToDisclose bit=0,                            
@roleXml text=null,                              
@startDate datetime=null,                                  
@endDate datetime=null,                                 
@board varchar(4000)=null,                             
@boardCommittee varchar(4000)=null,                              
@hospitalCommittee varchar(4000)=null,                                
@outSideEntityName varchar(4000)=null,                                  
@businessNature varchar(4000)=null,                                  
@companyType varchar(4000)=null,                             
@percentageTotalEquityOwned varchar(4000)=null,                                  
                               
@chart1ServiceProvided Varchar(4000)=null,                                  
@chart1AnnualEquityCompensation varchar(4000)=null,                                  
@chart1FiduciaryPosition varchar(4000)=null,                                  
@chart1ValueOfEquityOwned varchar(4000)=null,                                  
@chart1WrittenAgreement varchar(4000)=null,                                  
@chart1DaysOfOutsideActivity int=null,                                  
@chart1IsAggregate bit=null,                                  
@chart1AnnualCashCompensation varchar(4000)=null,                              
                            
@chart2ValueOfEquityInterest varchar(4000)=null,                            
                            
@chart3FamilyMember varchar(4000)=null,                                
@chart3FamilyMemberAssociation varchar(4000)=null,                            
@chart3ValueOfEquityInterest varchar(4000)=null,                            
                            
@trusteeNonPartnersAssociationChart1 varchar(4000)=null,                            
@trusteeDescOfOutsideEntityChart1 varchar(4000)=null,                            
@trusteeFamilyMemberChart2 varchar(4000)=null,                            
                             
@sortColumn varchar(150)='name',                             
@sortOrder bit=1,-->Asc 0-->Descending                      
@selectedChartXml text=null                                 
)                                            
AS BEGIN                                            
                                            
SET NOCOUNT ON                                            
                                
if(@firstName is null)                                            
 Set @firstName='%'                                            
else                                            
 Set @firstName=@firstName+'%'                                             
                                            
if(@lastName is null)                                            
 Set @lastName='%'                                            
else                                            
 Set @lastName=@lastName+'%'                                             
                                            
if(@startDate is null)                                          
  Select @startDate=cast('1900-01-01' as datetime)              
                                
if(@endDate is null)                              
 Set @endDate= GetDate()         
        
declare @roleTable table (Sequence int identity, COIRole varchar(75))                          
declare @organizationTable table (Sequence int identity, Organization varchar(75))                      
declare @chartsTable table(Sequence   int identity,chart varchar(75))                                         
                    
-------Get the COIIDs matching the preliminary search parameters(i.e firstname,lastname,username,date,status etc)-----        
--This step will narrow down the no.of records on which the advanced search(determined by the passed in parameters) will be performed-----                         
Declare @temp as table(coiId int)     
if @username is null     
 BEGIN                              
    Insert into @temp SELECT  Max(COI.[Id]) as COIID                              
   from AdmPerson adp                       
   INNER JOIN ConflictOfInterest coi                                  
    On   adp.[LastName] like @lastName                
    AND adp.[FirstName] like @firstName                                   
    AND coi.[admPersonId]=adp.[Id]          
    AND (DateDiff(day,@startDate ,coi.[datesubmitted])  >= 0)                 
    AND (DateDiff(day,@endDate,coi.[datesubmitted])  <= 0)                                
    AND [Status]in ('COISTATUS_SUBMITTED','COISTATUS_REVIEWED')                                               
  INNER JOIN COI_QuestionnaireAnswer_map cqm                                  
    On cqm.COIID = coi.[Id]                               
   INNER JOIN QuestionnaireAnswer qa                                  
    On qa.[Id]=cqm.[QuestionnaireAnswerId]                
  where                                        
    (isnull(cast(coi.[HasOutsideActivities] as varchar(1)),'*') like Case @nothingToDisclose                                            
     When 0 then '%'                                    
     else                                     
     '0'                                    
     END                          
   and  isnull(cast(coi.[HasEquityInterests] as varchar(1)),'*')like Case @nothingToDisclose                                            
     When 0 then '%'                                    
     else                                     
     '0'                                    
     END                           
   and isnull(cast(coi.[HasFamilyAssociations]as varchar(1)),'*') like Case @nothingToDisclose                                            
     When 0 then '%'                                    
     else                                     
     '0'                                    
     END )        
                                    
  group by adp.[ID]                              
  Order by adp.[Id]      
END    
ELSE    
 BEGIN    
 Set @userName=@userName+'%'    
   Insert into @temp SELECT  Max(COI.[Id]) as COIID                              
   from AdmPerson adp                       
   INNER JOIN ConflictOfInterest coi                                  
    On   adp.[LastName] like @lastName                
    AND adp.[FirstName] like @firstName                                   
    AND coi.[admPersonId]=adp.[Id]          
    AND (DateDiff(day,@startDate ,coi.[datesubmitted])  >= 0)                 
    AND (DateDiff(day,@endDate,coi.[datesubmitted])  <= 0)                                
    AND [Status]in ('COISTATUS_SUBMITTED','COISTATUS_REVIEWED')                                               
   LEFT OUTER JOIN FwkDomainUser fdu                       
    On adp.[FwkDomainUserId]=fdu.[Id]                               
   INNER JOIN COI_QuestionnaireAnswer_map cqm                                  
    On cqm.COIID = coi.[Id]                  
   INNER JOIN QuestionnaireAnswer qa                                  
    On qa.[Id]=cqm.[QuestionnaireAnswerId]                
    AND fdu.UserName like @userName                
   where                                        
    (isnull(cast(coi.[HasOutsideActivities] as varchar(1)),'*') like Case @nothingToDisclose                                            
     When 0 then '%'                                    
     else                                     
     '0'                                    
     END                          
   and  isnull(cast(coi.[HasEquityInterests] as varchar(1)),'*')like Case @nothingToDisclose                                            
     When 0 then '%'                                    
     else                                     
     '0'                                    
     END                           
   and isnull(cast(coi.[HasFamilyAssociations]as varchar(1)),'*') like Case @nothingToDisclose                                            
     When 0 then '%'                                    
     else                                     
     '0'                                    
     END )        
                                    
  group by adp.[ID]                              
  Order by adp.[Id]    
 END                            
                        
-------------------------------------------Operational Logic----------------------------------------        
/*        
Using the COIIds obtained from the preliminary search,apply the advanced search(parameters passed in to further filter the results)        
Sorting will be applied on the final records yielded         
*/        
        
---------Get the COIIds matching the board committee search parameter--------------                             
Declare @tempMatchedRecords  as table(refIndex int ,cOIId int)                            
Declare @refIndex as int                      
Set @refIndex=1                           
insert into @tempMatchedRecords Select @refIndex,COIId from @temp         
        
                     
--*********Load the seleted charts in to a temporary table that will be joined for answers*****--------                  
if @selectedChartXml is not null                  
 BEGIN                  
  declare @xmlchartDoc int                             
  exec sp_xml_preparedocument @xmlchartDoc output, @selectedChartXml                                  
  insert into @chartsTable select [Col1] from openxml(@xmlchartDoc, '//Table1',2) with (Col1 varchar(75))                        
  exec sp_xml_removedocument @xmlchartDoc                   
 END                  
---------***************** Organization search(Common section of reports)*****************------------------               
if(@organizationXml is not null)                      
BEGIN                      
Set @refIndex=@refIndex+1                      
 declare @xmlOrgDoc int                         
 exec sp_xml_preparedocument @xmlOrgDoc output, @organizationXml                                  
 insert into @organizationTable select [Col1] from openxml(@xmlOrgDoc, '//Table1',2) with (Col1 varchar(75))                                                
 exec sp_xml_removedocument @xmlOrgDoc                                            
 insert into @tempMatchedRecords Select distinct @refIndex, t.COIId  from (Select COIId ,QuestionnaireAnswerId from COI_QuestionnaireAnswer_map where COIId in (Select COIId from @temp) ) t  INNER join Answer a                               
      on t.questionnaireAnswerID=a.QuestionnaireAnswerID                        
 and (Lower(a.[Name])='organization')                      
      Inner Join @organizationTable ot                      
  On ot.[Organization]=a.[Value]                       
if not exists(Select 1 from @tempMatchedRecords where refIndex=@refIndex)                      
Return                      
END            
        
---------*******************COI Role search(Common Section of repots)************************---------------                         
if(@roleXml is not null )                      
Begin         
declare @xmlRoleDoc int                         
 exec sp_xml_preparedocument @xmlRoleDoc output, @roleXml                                  
 insert into @roleTable select [Col1] from openxml(@xmlRoleDoc, '//Table1',2) with (Col1 varchar(75))                                           
 exec sp_xml_removedocument @xmlRoleDoc                      
                       
 Set @refIndex=@refIndex+1                                           
  insert into @tempMatchedRecords         
   Select distinct @refIndex, t.COIId  from @temp t        
    inner join conflictOfinterest coi        
    On coi.[Id]=t.CoiId        
    inner join admperson adp        
    on coi.[admpersonId]=adp.[Id]        
    inner join @roleTable rt        
    on rt.[COIRole]=adp.[COIRole]        
                       
 if not exists(Select 1 from @tempMatchedRecords where refIndex=@refIndex)                      
Return                      
END                       
---------*******************Board committee search(Common Section of repots)****************---------------                         
if(@boardCommittee is not null )                      
Begin                        
 Set @refIndex=@refIndex+1                                           
  insert into @tempMatchedRecords Select distinct @refIndex, t.COIId  from (Select COIId ,QuestionnaireAnswerId from COI_QuestionnaireAnswer_map where COIId in (Select COIId from @temp) ) t                        
    INNER join Answer a                               
     on t.questionnaireAnswerID=a.QuestionnaireAnswerID                       
     and (isNULL(a.[Value],'*') Like @boardCommittee and (Lower(a.[Name])='boardcommitteelist'))                       
 if not exists(Select 1 from @tempMatchedRecords where refIndex=@refIndex)                      
Return                      
END                            
---------*******************Board search(Common Section of repots)************************---------------                                              
                             
if(@board is not null )                       
BEGIN                                           
Set @refIndex=@refIndex+1                            
 insert into @tempMatchedRecords Select distinct @refIndex, t.COIId  from (Select COIId ,QuestionnaireAnswerId from COI_QuestionnaireAnswer_map where COIId in (Select COIId from @temp) ) t  INNER join Answer a                               
      on t.questionnaireAnswerID=a.QuestionnaireAnswerID and                              
      (isNULL(a.[Value],'*') Like @board and (Lower(a.[Name])='boardlist'))                      
                       
if not exists(Select 1 from @tempMatchedRecords where refIndex=@refIndex)                        
Return                      
END                            
---------*******************Hospital committee search(Common Section of repots)*****************---------------                                              
--                             
if(@hospitalCommittee is not null )                      
BEGIN                                            
Set @refIndex=@refIndex+1                            
 insert into @tempMatchedRecords Select distinct @refIndex, t.COIId  from (Select COIId ,QuestionnaireAnswerId from COI_QuestionnaireAnswer_map where COIId in (Select COIId from @temp) ) t  INNER join Answer a                               
      on t.questionnaireAnswerID=a.QuestionnaireAnswerID and                              
      (isNULL(a.[Value],'*') Like @hospitalCommittee and (Lower(a.[Name])='hospitalcommittees'))                       
  if not exists(Select 1 from @tempMatchedRecords where refIndex=@refIndex)                        
Return                      
END    
                  
Declare @tempMatchedCharts  as table(cOIId int,qName varchar(150),ansName varchar(150),ansValue varchar(150))  
---------****************Select COIs containing only those charts selected in the report**************-----------  
if @selectedChartXml is not null                      
    BEGIN    
  insert into @tempMatchedCharts                 
     Select distinct t.COIId ,q.[Name],a.[Name],a.[Value] from       
    (Select temp.COIId,QuestionnaireAnswerId  from COI_QuestionnaireAnswer_map chm       
     inner join @temp temp       
      On temp.COIID is not null       
      and chm.COIId =temp.COIID       
      and chm.QuestionnaireAnswerID is not null) t       
     inner join Answer a                 
    On t.questionnaireAnswerID=a.QuestionnaireAnswerID                         
      Inner Join Questionnaireanswer qa                      
    On qa.[Id]=t.questionnaireAnswerID                      
      Inner Join QuestionnaireVersion qv                       
    On qv.[Id]=qa.[QuestionnaireVersionId]                      
      Inner Join Questionnaire q                   
    On q.[Id]=qv.[QuestionnaireId]  
    and t.COIID is not null  
  
 if exists(Select chart from @chartsTable where chart='chart1')    
  BEGIN  
   Set @refIndex=@refIndex+1  
   insert into @tempMatchedRecords   
   Select distinct @refIndex, t.COIId from @tempMatchedCharts t where t.qname='your outside activities'  
   and t.COIID is not null   
   if not exists(Select 1 from @tempMatchedRecords where refIndex=@refIndex)                   
   Return       
  END   
 if exists(Select chart from @chartsTable where chart='chart2')    
  BEGIN  
   Set @refIndex=@refIndex+1  
   insert into @tempMatchedRecords   
   Select distinct @refIndex, t.COIId from @tempMatchedCharts t where t.qname='your equity interests'  
   and t.COIID is not null  
    if not exists(Select 1 from @tempMatchedRecords where refIndex=@refIndex)                   
   Return        
  END   
 if exists(Select chart from @chartsTable where chart='chart3')    
  BEGIN  
   Set @refIndex=@refIndex+1  
   insert into @tempMatchedRecords   
   Select distinct @refIndex, t.COIId from @tempMatchedCharts t where t.qname='your family''s associations and equity interests'  
   and t.COIID is not null  
    if not exists(Select 1 from @tempMatchedRecords where refIndex=@refIndex)                   
   Return        
  END   
  if exists(Select chart from @chartsTable where chart='trusteechart1')  
  BEGIN  
   Set @refIndex=@refIndex+1  
   insert into @tempMatchedRecords   
   Select distinct @refIndex, t.COIId from @tempMatchedCharts t where t.qname='trustee association'  
    and t.COIID is not null  
    if not exists(Select 1 from @tempMatchedRecords where refIndex=@refIndex)                   
   Return    
  END  
 if exists(Select chart from @chartsTable where chart='trusteechart2')  
  BEGIN  
   Set @refIndex=@refIndex+1  
   insert into @tempMatchedRecords   
   Select distinct @refIndex, t.COIId from @tempMatchedCharts t where t.qname='trustee''s family associations and equity interests'  
   and t.COIID is not null   
   if not exists(Select 1 from @tempMatchedRecords where refIndex=@refIndex)                   
   Return   
  END      
 END       
  
---------*******************Outside entity search(can be performed specific to charts as well as across charts)*****************---------------                                                                  
if(@outSideEntityName is not null )                      
BEGIN                                            
               
 Set @outSideEntityName=@outSideEntityName+'%'   
if exists (Select 1 from @chartsTable)  
 BEGIN    
 if exists(Select chart from @chartsTable where chart='chart1')    
  BEGIN  
   Set @refIndex=@refIndex+1  
   insert into @tempMatchedRecords   
   Select distinct @refIndex, t.COIId from @tempMatchedCharts t where t.qname='your outside activities'  
   and (isNULL(t.[ansValue],'*') Like @outSideEntityName and (Lower(t.[ansName])='outsideentityname'))                    
      and t.COIID is not null   
   if not exists(Select 1 from @tempMatchedRecords where refIndex=@refIndex)                   
   Return       
  END   
 if exists(Select chart from @chartsTable where chart='chart2')    
  BEGIN  
   Set @refIndex=@refIndex+1  
   insert into @tempMatchedRecords   
   Select distinct @refIndex, t.COIId from @tempMatchedCharts t where t.qname='your equity interests'  
   and (isNULL(t.[ansValue],'*') Like @outSideEntityName and (Lower(t.[ansName])='outsideentityname'))                    
      and t.COIID is not null  
    if not exists(Select 1 from @tempMatchedRecords where refIndex=@refIndex)                   
   Return        
  END   
 if exists(Select chart from @chartsTable where chart='chart3')    
  BEGIN  
   Set @refIndex=@refIndex+1  
   insert into @tempMatchedRecords   
   Select distinct @refIndex, t.COIId from @tempMatchedCharts t where t.qname='your family''s associations and equity interests'  
   and (isNULL(t.[ansValue],'*') Like @outSideEntityName and (Lower(t.[ansName])='outsideentityname'))                    
      and t.COIID is not null  
    if not exists(Select 1 from @tempMatchedRecords where refIndex=@refIndex)                   
   Return        
  END   
  if exists(Select chart from @chartsTable where chart='trusteechart1')  
  BEGIN  
   Set @refIndex=@refIndex+1  
   insert into @tempMatchedRecords   
   Select distinct @refIndex, t.COIId from @tempMatchedCharts t where t.qname='trustee association'  
   and (isNULL(t.[ansValue],'*') Like @outSideEntityName and (Lower(t.[ansName])='outsideentityname'))                    
      and t.COIID is not null  
    if not exists(Select 1 from @tempMatchedRecords where refIndex=@refIndex)                   
   Return    
  END  
 if exists(Select chart from @chartsTable where chart='trusteechart2')  
  BEGIN  
   Set @refIndex=@refIndex+1  
   insert into @tempMatchedRecords   
   Select distinct @refIndex, t.COIId from @tempMatchedCharts t where t.qname='trustee''s family associations and equity interests'  
   and (isNULL(t.[ansValue],'*') Like @outSideEntityName and (Lower(t.[ansName])='outsideentityname'))                    
      and t.COIID is not null   
   if not exists(Select 1 from @tempMatchedRecords where refIndex=@refIndex)                   
   Return   
  END   
 END  
ELSE  
 BEGIN  
  Set @refIndex=@refIndex+1  
  insert into @tempMatchedRecords           
     Select distinct @refIndex,chm.COIId from COI_QuestionnaireAnswer_map chm           
   inner join @temp temp           
    On chm.COIId =temp.COIID           
    and chm.QuestionnaireAnswerID is not null           
   inner join answer a on chm.questionnaireAnswerID=a.QuestionnaireAnswerID            
    and (isNULL(a.[Value],'*') Like @outSideEntityName and (Lower(a.[Name])='outsideentityname'))   
 END      
END                    
---------*******************Business nature search(can be performed specific to charts as well as across charts)*****************---------------                                                                  
                            
if(@businessNature is not null )                      
 BEGIN  
 if exists (Select 1 from @chartsTable)  
 BEGIN           
  if exists(Select chart from @chartsTable where chart='chart1')    
   BEGIN  
    Set @refIndex=@refIndex+1  
    insert into @tempMatchedRecords   
    Select distinct @refIndex, t.COIId from @tempMatchedCharts t where t.qname='your outside activities'  
    and (isNULL(t.[ansValue],'*') Like @businessNature and (Lower(t.[ansName])='briefdescriptionofbusiness'))                    
    and t.COIID is not null   
    if not exists(Select 1 from @tempMatchedRecords where refIndex=@refIndex)                   
    Return       
   END   
  if exists(Select chart from @chartsTable where chart='chart2')    
   BEGIN  
    Set @refIndex=@refIndex+1  
    insert into @tempMatchedRecords   
    Select distinct @refIndex, t.COIId from @tempMatchedCharts t where t.qname='your equity interests'  
    and (isNULL(t.[ansValue],'*') Like @businessNature and (Lower(t.[ansName])='briefdescriptionofbusiness'))                    
    and t.COIID is not null  
     if not exists(Select 1 from @tempMatchedRecords where refIndex=@refIndex)                   
    Return        
   END   
  if exists(Select chart from @chartsTable where chart='chart3')    
   BEGIN  
    Set @refIndex=@refIndex+1  
    insert into @tempMatchedRecords   
    Select distinct @refIndex, t.COIId from @tempMatchedCharts t where t.qname='your family''s associations and equity interests'  
    and (isNULL(t.[ansValue],'*') Like @businessNature and (Lower(t.[ansName])='briefdescriptionofbusiness'))                    
    and t.COIID is not null  
     if not exists(Select 1 from @tempMatchedRecords where refIndex=@refIndex)                   
    Return        
   END   
   if exists(Select chart from @chartsTable where chart='trusteechart1')  
   BEGIN  
    Set @refIndex=@refIndex+1  
    insert into @tempMatchedRecords   
    Select distinct @refIndex, t.COIId from @tempMatchedCharts t where t.qname='trustee association'  
    and (isNULL(t.[ansValue],'*') Like @businessNature and (Lower(t.[ansName])='briefdescriptionofbusiness'))                    
    and t.COIID is not null  
     if not exists(Select 1 from @tempMatchedRecords where refIndex=@refIndex)                   
    Return    
   END  
  if exists(Select chart from @chartsTable where chart='trusteechart2')  
   BEGIN  
    Set @refIndex=@refIndex+1  
    insert into @tempMatchedRecords   
    Select distinct @refIndex, t.COIId from @tempMatchedCharts t where t.qname='trustee''s family associations and equity interests'  
    and (isNULL(t.[ansValue],'*') Like @businessNature and (Lower(t.[ansName])='briefdescriptionofbusiness'))                    
    and t.COIID is not null   
    if not exists(Select 1 from @tempMatchedRecords where refIndex=@refIndex)                   
    Return   
   END   
 END  
ELSE  
 BEGIN  
  Set @refIndex=@refIndex+1  
  insert into @tempMatchedRecords           
     Select distinct @refIndex,chm.COIId from COI_QuestionnaireAnswer_map chm           
   inner join @temp temp           
    On chm.COIId =temp.COIID           
    and chm.QuestionnaireAnswerID is not null           
   inner join answer a on chm.questionnaireAnswerID=a.QuestionnaireAnswerID            
    and (isNULL(a.[Value],'*') Like @businessNature and (Lower(a.[Name])='briefdescriptionofbusiness'))   
 END     
END                    
                        
---------*******************Company Type Search(can be performed specific to charts as well as across charts)*****************---------------                                                                                       
if(@companyType is not null )                        
BEGIN    
if exists (Select 1 from @chartsTable)  
 BEGIN    
 if exists(Select chart from @chartsTable where chart='chart1')    
  BEGIN  
   Set @refIndex=@refIndex+1  
   insert into @tempMatchedRecords   
   Select distinct @refIndex, t.COIId from @tempMatchedCharts t where t.qname='your outside activities'  
   and (isNULL(t.[ansValue],'*') Like @companyType and (Lower(t.[ansName])='public'))                    
      and t.COIID is not null   
   if not exists(Select 1 from @tempMatchedRecords where refIndex=@refIndex)                   
   Return       
  END   
 if exists(Select chart from @chartsTable where chart='chart2')    
  BEGIN  
   Set @refIndex=@refIndex+1  
   insert into @tempMatchedRecords   
   Select distinct @refIndex, t.COIId from @tempMatchedCharts t where t.qname='your equity interests'  
   and (isNULL(t.[ansValue],'*') Like @companyType and (Lower(t.[ansName])='public'))                    
      and t.COIID is not null  
    if not exists(Select 1 from @tempMatchedRecords where refIndex=@refIndex)                   
   Return        
  END   
 if exists(Select chart from @chartsTable where chart='chart3')    
  BEGIN  
   Set @refIndex=@refIndex+1  
   insert into @tempMatchedRecords   
   Select distinct @refIndex, t.COIId from @tempMatchedCharts t where t.qname='your family''s associations and equity interests'  
   and (isNULL(t.[ansValue],'*') Like @companyType and (Lower(t.[ansName])='public'))                    
      and t.COIID is not null  
    if not exists(Select 1 from @tempMatchedRecords where refIndex=@refIndex)                   
   Return        
  END   
  if exists(Select chart from @chartsTable where chart='trusteechart1')  
  BEGIN  
   Set @refIndex=@refIndex+1  
   insert into @tempMatchedRecords   
   Select distinct @refIndex, t.COIId from @tempMatchedCharts t where t.qname='trustee association'  
   and (isNULL(t.[ansValue],'*') Like @companyType and (Lower(t.[ansName])='public'))                    
      and t.COIID is not null  
    if not exists(Select 1 from @tempMatchedRecords where refIndex=@refIndex)                   
   Return    
  END  
 if exists(Select chart from @chartsTable where chart='trusteechart2')  
  BEGIN  
   Set @refIndex=@refIndex+1  
   insert into @tempMatchedRecords   
   Select distinct @refIndex, t.COIId from @tempMatchedCharts t where t.qname='trustee''s family associations and equity interests'  
   and (isNULL(t.[ansValue],'*') Like @companyType and (Lower(t.[ansName])='public'))                    
      and t.COIID is not null   
   if not exists(Select 1 from @tempMatchedRecords where refIndex=@refIndex)                   
   Return   
  END  
 END    
ELSE  
 BEGIN  
  Set @refIndex=@refIndex+1  
  insert into @tempMatchedRecords           
     Select distinct @refIndex,chm.COIId from COI_QuestionnaireAnswer_map chm           
   inner join @temp temp           
    On chm.COIId =temp.COIID           
    and chm.QuestionnaireAnswerID is not null           
   inner join answer a on chm.questionnaireAnswerID=a.QuestionnaireAnswerID            
    and (isNULL(a.[Value],'*') Like @companyType and (Lower(a.[Name])='public'))   
 END              
END              
                          
---------******Percentage total equity owned Search(can be performed specific to charts as well as across charts)*****************---------------                                                                                  
if(@percentageTotalEquityOwned is not null)                      
BEGIN         
if exists (Select 1 from @chartsTable)  
 BEGIN  
 if exists(Select chart from @chartsTable where chart='chart1')    
  BEGIN  
   Set @refIndex=@refIndex+1  
   insert into @tempMatchedRecords   
   Select distinct @refIndex, t.COIId from @tempMatchedCharts t where t.qname='your outside activities'  
   and (isNULL(t.[ansValue],'*') Like @percentageTotalEquityOwned and (Lower(t.[ansName])='totalpercentequityowned'))                    
      and t.COIID is not null   
   if not exists(Select 1 from @tempMatchedRecords where refIndex=@refIndex)                   
   Return       
  END   
 if exists(Select chart from @chartsTable where chart='chart2')    
  BEGIN  
   Set @refIndex=@refIndex+1  
   insert into @tempMatchedRecords   
   Select distinct @refIndex, t.COIId from @tempMatchedCharts t where t.qname='your equity interests'  
   and (isNULL(t.[ansValue],'*') Like @percentageTotalEquityOwned and (Lower(t.[ansName])='totalpercentequityowned'))                    
      and t.COIID is not null  
    if not exists(Select 1 from @tempMatchedRecords where refIndex=@refIndex)                   
   Return        
  END   
 if exists(Select chart from @chartsTable where chart='chart3')    
  BEGIN  
   Set @refIndex=@refIndex+1  
   insert into @tempMatchedRecords   
   Select distinct @refIndex, t.COIId from @tempMatchedCharts t where t.qname='your family''s associations and equity interests'  
   and (isNULL(t.[ansValue],'*') Like @percentageTotalEquityOwned and (Lower(t.[ansName])='totalpercentequityowned'))                    
      and t.COIID is not null  
    if not exists(Select 1 from @tempMatchedRecords where refIndex=@refIndex)                   
   Return        
  END   
  if exists(Select chart from @chartsTable where chart='trusteechart1')  
  BEGIN  
   Set @refIndex=@refIndex+1  
   insert into @tempMatchedRecords   
   Select distinct @refIndex, t.COIId from @tempMatchedCharts t where t.qname='trustee association'  
   and (isNULL(t.[ansValue],'*') Like @percentageTotalEquityOwned and (Lower(t.[ansName])='totalpercentequityowned'))                    
      and t.COIID is not null  
    if not exists(Select 1 from @tempMatchedRecords where refIndex=@refIndex)                   
   Return    
  END  
 if exists(Select chart from @chartsTable where chart='trusteechart2')  
  BEGIN  
   Set @refIndex=@refIndex+1  
   insert into @tempMatchedRecords   
   Select distinct @refIndex, t.COIId from @tempMatchedCharts t where t.qname='trustee''s family associations and equity interests'  
   and (isNULL(t.[ansValue],'*') Like @percentageTotalEquityOwned and (Lower(t.[ansName])='totalpercentequityowned'))                    
      and t.COIID is not null   
   if not exists(Select 1 from @tempMatchedRecords where refIndex=@refIndex)                   
   Return   
  END   
 END     
ELSE  
 BEGIN  
  Set @refIndex=@refIndex+1  
  insert into @tempMatchedRecords           
     Select distinct @refIndex,chm.COIId from COI_QuestionnaireAnswer_map chm           
   inner join @temp temp           
    On chm.COIId =temp.COIID           
    and chm.QuestionnaireAnswerID is not null           
   inner join answer a on chm.questionnaireAnswerID=a.QuestionnaireAnswerID            
    and (isNULL(a.[Value],'*') Like @percentageTotalEquityOwned and (Lower(a.[Name])='totalpercentequityowned'))   
 END          
END                   
---------*******************Service type search(Search on chart1)*****************---------------                                                                                       
if(@chart1ServiceProvided is not null )                      
BEGIN                                            
 Set @refIndex=@refIndex+1                            
  insert into @tempMatchedRecords         
    Select distinct @refIndex,chm.COIId from         
     COI_QuestionnaireAnswer_map chm         
     inner join @temp temp         
      On chm.COIId =temp.COIID and chm.QuestionnaireAnswerID is not null         
     inner join   answer a         
      on chm.questionnaireAnswerID=a.QuestionnaireAnswerID         
      and (isNULL(a.[Value],'*') Like @chart1ServiceProvided         
      and (Lower(a.[Name])='descrserviceprovide'))                      
 if not exists(Select 1 from @tempMatchedRecords where refIndex=@refIndex)                        
Return                      
END                               
---------*******************Annual equity compensation search(Search on chart1)*****************---------------                                                                                                             
if(@chart1AnnualEquityCompensation is not null )                      
BEGIN                                            
 Set @refIndex=@refIndex+1                            
  insert into @tempMatchedRecords         
    Select distinct @refIndex,t.COIId  from         
    (Select COIId,QuestionnaireAnswerId  from COI_QuestionnaireAnswer_map where COIId in (Select COIId from @temp) ) t          
    INNER join Answer a                               
     on t.questionnaireAnswerID=a.QuestionnaireAnswerID         
      and (isNULL(a.[Value],'*') Like @chart1AnnualEquityCompensation and (Lower(a.[Name])='annualequity'))                      
 if not exists(Select 1 from @tempMatchedRecords where refIndex=@refIndex)                        
 Return                      
END                               
---------*******************Fiduciary position search(Search on chart1)*****************---------------                                                                                                             
if(@chart1FiduciaryPosition is not null )                      
BEGIN                                            
 Set @refIndex=@refIndex+1                            
  insert into @tempMatchedRecords         
    Select distinct @refIndex,chm.COIId from COI_QuestionnaireAnswer_map chm         
     inner join @temp temp         
      On chm.COIId =temp.COIID and chm.QuestionnaireAnswerID is not null         
     inner join   answer a         
      on chm.questionnaireAnswerID=a.QuestionnaireAnswerID          
      and (isNULL(a.[Value],'*') Like @chart1FiduciaryPosition and (Lower(a.[Name])='position'))                       
 if not exists(Select 1 from @tempMatchedRecords where refIndex=@refIndex)                      
 Return                      
END                              
--                              
---------*******************aggregate or equity owned search(Search on chart1)*****************---------------                                                                                                             
if ((@chart1IsAggregate =1) and (@chart1ValueOfEquityOwned is not null))                          
 Begin                          
  Set @refIndex=@refIndex+1                          
   insert into @tempMatchedRecords         
     Select distinct @refIndex ,t.COIId  from         
      (Select COIId,QuestionnaireAnswerId from COI_QuestionnaireAnswer_map         
        where COIId in (Select COIId from @temp) ) t          
      INNER join conflictOfInterest coi                         
       On coi.[Id]=t.COIId                          
       AND isNULL(cast(coi.[aggregateEquity] as varchar(15)),'*') = @chart1ValueOfEquityOwned                             
 END                          
ELSE If(@chart1ValueOfEquityOwned is not null )                          
  BEGIN                                            
  Set @refIndex=@refIndex+1                            
   insert into @tempMatchedRecords         
     Select distinct @refIndex,chm.COIId from COI_QuestionnaireAnswer_map chm         
      inner join @temp temp         
       On chm.COIId =temp.COIID         
       and chm.QuestionnaireAnswerID is not null         
      inner join answer a on chm.questionnaireAnswerID=a.QuestionnaireAnswerID          
       and (isNULL(a.[Value],'*') Like @chart1ValueOfEquityOwned and (Lower(a.[Name])='totalequityowned'))                          
  END                       
if not exists(Select 1 from @tempMatchedRecords where refIndex=@refIndex)                      
Return                      
                   
---------*******************written agreement search(Search on chart1)*****************---------------                      
if(@chart1WrittenAgreement is not null )                       
BEGIN                                           
 Set @refIndex=@refIndex+1                            
  insert into @tempMatchedRecords        
    Select distinct @refIndex,chm.COIId from COI_QuestionnaireAnswer_map chm         
  inner join @temp temp         
    On chm.COIId =temp.COIID and chm.QuestionnaireAnswerID is not null         
  inner join   answer a         
    on chm.questionnaireAnswerID=a.QuestionnaireAnswerID          
    and (isNULL(a.[Value],'*') Like @chart1WrittenAgreement and (Lower(a.[Name])='writtenagreement'))                        
                       
 if not exists(Select 1 from @tempMatchedRecords where refIndex=@refIndex)                        
 Return                      
END                              
---------*******************Days of outside activity search(Search on chart1)*****************---------------                                                                                                             
if(@chart1DaysOfOutsideActivity is not null )                      
BEGIN                                            
Set @refIndex=@refIndex+1                            
  insert into @tempMatchedRecords         
    Select  distinct @refIndex,chm.COIId from COI_QuestionnaireAnswer_map chm         
     inner join @temp temp         
      On chm.COIId =temp.COIID and chm.QuestionnaireAnswerID is not null         
     inner join   answer a         
      on chm.questionnaireAnswerID=a.QuestionnaireAnswerID          
      and                                          
      (cast(isNULL(a.[Value],0)as float) >= cast(@chart1DaysOfOutsideActivity as float) and (Lower(a.[Name])='timespent'))                  
        
 if not exists(Select 1 from @tempMatchedRecords where refIndex=@refIndex)                       
 Return                      
END      
---------*******************annual cash compensation search(Search on chart1)*****************---------------                                                                                                             
if(@chart1AnnualCashCompensation is not null )                       
BEGIN                                           
 Set @refIndex=@refIndex+1                            
  insert into @tempMatchedRecords         
    Select distinct @refIndex,chm.COIId from COI_QuestionnaireAnswer_map chm         
     inner join @temp temp         
      On chm.COIId =temp.COIID         
      and chm.QuestionnaireAnswerID is not null         
     inner join answer a         
      on chm.questionnaireAnswerID=a.QuestionnaireAnswerID          
      and                                          
      (isNULL(a.[Value],'*') Like cast(@chart1AnnualCashCompensation as varchar(30))and (Lower(a.[Name])='annualcashcomp'))                             
 if not exists(Select 1 from @tempMatchedRecords where refIndex=@refIndex)                      
 Return                      
END                      
                         
---------*******************value of equity interest search(Search on chart2)*****************---------------                                                                                                             
if(@chart2ValueOfEquityInterest is not null )                      
BEGIN                                            
 Set @refIndex=@refIndex+1                           
  insert into @tempMatchedRecords         
   Select  distinct @refIndex,chm.COIId from COI_QuestionnaireAnswer_map chm         
    inner join @temp temp         
     On chm.COIId =temp.COIID         
     and chm.QuestionnaireAnswerID is not null         
    inner join answer a         
     on chm.questionnaireAnswerID=a.QuestionnaireAnswerID         
     and (isNULL(a.[Value],'*') Like cast(@chart2ValueOfEquityInterest as varchar(30))and (Lower(a.[Name])='valueofequity'))                            
 if not exists(Select 1 from @tempMatchedRecords where refIndex=@refIndex)                        
 Return                      
END                      
---------*****Family member search(Search on chart3(Individual) and chart2(Trustee))*****************---------------                                  
            
if(@chart3FamilyMember is not null or @trusteeFamilyMemberChart2 is not null )                       
BEGIN        
if exists(Select chart from @chartsTable where chart='chart1')    
  BEGIN  
   Set @refIndex=@refIndex+1  
   insert into @tempMatchedRecords   
   Select distinct @refIndex, t.COIId from @tempMatchedCharts t where t.qname='your outside activities'  
   AND ((isNULL(t.[ansValue],'*') Like cast(@chart3FamilyMember as varchar(30))and (Lower(t.[ansName])='familymembertype'))or                  
   (isNULL(t.[ansValue],'*') Like cast(@trusteeFamilyMemberChart2 as varchar(30))and (Lower(t.[ansName])='familymembertype')))                     
      and t.COIID is not null   
   if not exists(Select 1 from @tempMatchedRecords where refIndex=@refIndex)                   
   Return       
  END   
 if exists(Select chart from @chartsTable where chart='chart2')    
  BEGIN  
   Set @refIndex=@refIndex+1  
   insert into @tempMatchedRecords   
   Select distinct @refIndex, t.COIId from @tempMatchedCharts t where t.qname='your equity interests'  
   AND ((isNULL(t.[ansValue],'*') Like cast(@chart3FamilyMember as varchar(30))and (Lower(t.[ansName])='familymembertype'))or                  
   (isNULL(t.[ansValue],'*') Like cast(@trusteeFamilyMemberChart2 as varchar(30))and (Lower(t.[ansName])='familymembertype')))                     
      and t.COIID is not null  
    if not exists(Select 1 from @tempMatchedRecords where refIndex=@refIndex)                   
   Return        
  END   
 if exists(Select chart from @chartsTable where chart='chart3')    
  BEGIN  
   Set @refIndex=@refIndex+1  
   insert into @tempMatchedRecords   
   Select distinct @refIndex, t.COIId from @tempMatchedCharts t where t.qname='your family''s associations and equity interests'  
   AND ((isNULL(t.[ansValue],'*') Like cast(@chart3FamilyMember as varchar(30))and (Lower(t.[ansName])='familymembertype'))or                  
   (isNULL(t.[ansValue],'*') Like cast(@trusteeFamilyMemberChart2 as varchar(30))and (Lower(t.[ansName])='familymembertype')))                     
      and t.COIID is not null  
    if not exists(Select 1 from @tempMatchedRecords where refIndex=@refIndex)                   
   Return        
  END   
  if exists(Select chart from @chartsTable where chart='trusteechart1')  
  BEGIN  
   Set @refIndex=@refIndex+1  
   insert into @tempMatchedRecords   
   Select distinct @refIndex, t.COIId from @tempMatchedCharts t where t.qname='trustee association'  
   AND ((isNULL(t.[ansValue],'*') Like cast(@chart3FamilyMember as varchar(30))and (Lower(t.[ansName])='familymembertype'))or                  
   (isNULL(t.[ansValue],'*') Like cast(@trusteeFamilyMemberChart2 as varchar(30))and (Lower(t.[ansName])='familymembertype')))                     
      and t.COIID is not null  
    if not exists(Select 1 from @tempMatchedRecords where refIndex=@refIndex)                   
   Return    
  END  
 if exists(Select chart from @chartsTable where chart='trusteechart2')  
  BEGIN  
   Set @refIndex=@refIndex+1  
   insert into @tempMatchedRecords   
   Select distinct @refIndex, t.COIId from @tempMatchedCharts t where t.qname='trustee''s family associations and equity interests'  
         AND ((isNULL(t.[ansValue],'*') Like cast(@chart3FamilyMember as varchar(30))and (Lower(t.[ansName])='familymembertype'))or                  
   (isNULL(t.[ansValue],'*') Like cast(@trusteeFamilyMemberChart2 as varchar(30))and (Lower(t.[ansName])='familymembertype')))                     
      and t.COIID is not null   
   if not exists(Select 1 from @tempMatchedRecords where refIndex=@refIndex)                   
   Return   
  END  
END                      
                       
---------*******************Family member association search(Search on chart3)*****************---------------                                                                                                             
if(@chart3FamilyMemberAssociation is not null )                      
BEGIN                                            
 Set @refIndex=@refIndex+1                            
  insert into @tempMatchedRecords         
    Select distinct @refIndex,chm.COIId from COI_QuestionnaireAnswer_map chm         
     inner join @temp temp         
      On chm.COIId =temp.COIID and chm.QuestionnaireAnswerID is not null         
     inner join   answer a         
      on chm.questionnaireAnswerID=a.QuestionnaireAnswerID          
      and                                         
      (isNULL(a.[Value],'*') Like cast(@chart3FamilyMemberAssociation as varchar(30))and (Lower(a.[Name])='familymemberrelationship'))                             
if not exists(Select 1 from @tempMatchedRecords where refIndex=@refIndex)                      
Return                      
END                      
---------**********value of equity interest search(Search on chart3)*****************---------------                                                                                                             
if(@chart3ValueOfEquityInterest is not null )                      
BEGIN                                            
Set @refIndex=@refIndex+1                            
   insert into @tempMatchedRecords         
    Select distinct @refIndex,chm.COIId from COI_QuestionnaireAnswer_map chm        
      inner join @temp temp         
      On chm.COIId =temp.COIID         
      and chm.QuestionnaireAnswerID is not null         
     inner join answer a         
      on chm.questionnaireAnswerID=a.QuestionnaireAnswerID         
      and                                          
      (isNULL(a.[Value],'*') Like cast(@chart3ValueOfEquityInterest as varchar(30))        
      and (Lower(a.[Name])='valueofequity'))                            
if not exists(Select 1 from @tempMatchedRecords where refIndex=@refIndex)                       
Return                      
END                      
---------*******************Non partners association search(Search on chart1(trustee))*****************---------------                                                                                                             
if(@trusteeNonPartnersAssociationChart1 is not null )                      
BEGIN                      
 Set @refIndex=@refIndex+1                            
  insert into @tempMatchedRecords         
    Select distinct @refIndex,chm.COIId from COI_QuestionnaireAnswer_map chm         
     inner join @temp temp         
      On chm.COIId =temp.COIID         
      and chm.QuestionnaireAnswerID is not null         
     inner join   answer a         
      on chm.questionnaireAnswerID=a.QuestionnaireAnswerID         
      and                                         
      (isNULL(a.[Value],'*') Like @trusteeNonPartnersAssociationChart1         
      and (Lower(a.[Name])='presentassociation'))                    
        
 if not exists(Select 1 from @tempMatchedRecords where refIndex=@refIndex)                       
 Return                      
END             
 ---------*******************description of outside entity search(Search on chart1(trustee))*****************---------------                                                                                                             
if(@trusteeDescOfOutsideEntityChart1 is not null )                       
BEGIN                                           
 Set @refIndex=@refIndex+1                            
  insert into @tempMatchedRecords         
    Select distinct @refIndex,chm.COIId from COI_QuestionnaireAnswer_map chm         
     inner join @temp temp         
      On chm.COIId =temp.COIID         
      and chm.QuestionnaireAnswerID is not null         
     inner join   answer a         
      on chm.questionnaireAnswerID=a.QuestionnaireAnswerID          
      and                                          
      (isNULL(a.[Value],'*') Like @trusteeDescOfOutsideEntityChart1         
      and (Lower(a.[Name])='briefdescriptionofbusiness'))                            
 if not exists(Select 1 from @tempMatchedRecords where refIndex=@refIndex)                        
Return          
END                           
                     
-------------------Sort the results sortcolumn(parameter)-------------------------------------                            
                
  Select  @refIndex= sum(Distinct (refIndex)) from @tempMatchedRecords where coiID is not null                          
 Declare @columnNameInLowerCase as varchar(150)                          
  Set @columnNameInLowerCase=Lower(@SortColumn)                      
  if @columnNameInLowerCase ='name'or @columnNameInLowerCase='title' or @columnNameInLowerCase='lastname' or @columnNameInLowerCase  ='supervisor'                          
   Begin        
 --Select * from  @tempMatchedRecords         
  Select T.COIid,coi.admpersonId as [Id],adp1.[Id]as SupervisorId from         
   (Select  COIId,Sum(Distinct(refIndex))as RefIndexSum from @tempMatchedRecords group by COIID)T                            
   inner join ConflictOfInterest coi                            
    On COI.Id=T.COIid                          
   Left Join admPerson adp                          
    On adp.ID=Coi.admpersonId              
   Left outer Join COI_Hierarchy_Map chm              
    On chm.ChildId=Adp.[Id]              
    and chm.Removed=0                       
   Left Outer Join AdmPerson adp1                       
    on adp1.[Id]=chm.parentId                                                              
    Where T.RefIndexSum=@refIndex                            
    AND T.COIid is not null                 
   Order by                           
    CASE @sortOrder                                    
      WHEN 0 THEN             
       Case  @columnNameInLowerCase                           
     When 'name' then adp.LastName                         
     When 'title' then adp.Title                        
     WHEN 'lastname' then adp.LastName                        
     WHEN 'supervisor' then adp1.LastName                          
     Else adp.LastName                           
       END            
    END DESC,            
      CASE @sortOrder                                    
      WHEN 1 then                          
       Case  @columnNameInLowerCase                           
     When 'name' then adp.LastName                         
     When 'title' then adp.Title                          
     WHEN 'lastname' then adp.LastName                          
     WHEN 'supervisor' then adp1.LastName                          
     Else adp.LastName                         
       END                                   
       END ,            
      Case @sortOrder            
       When 0 then            
     case @columnNameInLowerCase            
     When 'name' then adp.FirstName                        
     WHEN 'lastname' then adp.FirstName                        
     WHEN 'supervisor' then adp1.FirstName             
     END            
       END DESC,            
      Case @sortOrder            
       When 1 then            
     case @columnNameInLowerCase            
     When 'name' then adp.FirstName                        
     WHEN 'lastname' then adp.FirstName                        
     WHEN 'supervisor' then adp1.FirstName             
     END            
       END            
                              
 END                            
   ELSE IF @columnNameInLowerCase='policyviolation' or @columnNameInLowerCase='equityinterest'or @columnNameInLowerCase='familyinterest'or @columnNameInLowerCase='outsideactivity'or @columnNameInLowerCase='otheractivity'                          
 Begin                          
  Select T.COIid,coi.admpersonId as [Id],adp1.[Id]as SupervisorId
	from (Select COIId,Sum(Distinct(refIndex))as RefIndexSum from @tempMatchedRecords group by COIID)T                            
   inner join ConflictOfInterest coi                            
    On COI.Id=T.COIid                          
   Left Join admPerson adp                          
    On adp.ID=Coi.admpersonId
   Left outer Join COI_Hierarchy_Map chm              
    On chm.ChildId=adp.[Id]              
    and chm.Removed=0                       
   Left Outer Join AdmPerson adp1                       
    on adp1.[Id]=chm.parentId                          
    Where T.RefIndexSum=@refIndex                            
    AND T.COIid is not null                          
    Order by                           
    CASE @sortOrder                                    
      WHEN 1 THEN                                     
       CASE @sortColumn                                    
     WHEN 'policyviolation' THEN coi.PolicyViolation                                    
     WHEN 'equityinterest' THEN coi.HasEquityInterests                                
     WHEN 'familyinterest' THEN coi.HasFamilyAssociations                                
     WHEN 'outsideactivity' THEN coi.HasOutsideActivities                                
     WHEN 'otheractivity' THEN coi.OtherActivity                                       
     ELSE coi.PolicyViolation                                    
     END                                    
       END                                                 
       DESC,                                    
       CASE @sortOrder                                    
      WHEN 0 THEN                                     
       CASE @sortColumn                                    
     WHEN 'policyviolation' THEN coi.PolicyViolation                                    
     WHEN 'equityinterest' THEN coi.HasEquityInterests                                                                        
     WHEN 'familyinterest' THEN coi.HasFamilyAssociations                                    
     WHEN 'outsideactivity' THEN coi.HasOutsideActivities                                    
     WHEN 'otheractivity' THEN coi.OtherActivity                     
     ELSE coi.PolicyViolation     
       END                                    
       END                             
   END                          
  ELSE IF @columnNameInLowerCase='datesubmitted'                          
   Begin                          
   Select T.COIid,coi.admpersonId as [Id],adp1.[Id]as SupervisorId--adp.[LastName] 
	from (Select COIId,Sum(Distinct(refIndex))as RefIndexSum from @tempMatchedRecords group by COIID)T                            
    inner join ConflictOfInterest coi                            
     On COI.Id=T.COIid                          
    Left Join admPerson adp                          
     On adp.ID=Coi.admpersonId
	Left outer Join COI_Hierarchy_Map chm              
    On chm.ChildId=adp.[Id]              
    and chm.Removed=0                       
   Left Outer Join AdmPerson adp1                       
    on adp1.[Id]=chm.parentId                              
     Where T.RefIndexSum=@refIndex                            
     AND T.COIid is not null                          
    Order by                           
     CASE @sortOrder                                    
       WHEN 1 THEN                                     
        CASE @sortColumn                                    
      WHEN 'datesubmitted' THEN coi.DateSubmitted                                 
      END                                    
        END                                                 
        DESC,                                    
       CASE @sortOrder                                    
       WHEN 0 THEN                                     
        CASE @sortColumn                                    
       WHEN 'datesubmitted' THEN coi.DateSubmitted                                 
       END                          
        END                             
      END               
 END         
  


GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Creating [dbo].[MapBudgetFeed]'
GO


/***************************************************************************
* Name:			MapBudgetFeed
* Purpose:		Using table Stg_IE_AgrBudget_Ctl , map and validate
*				feed data.
*
* PARAMETERS
* Name				Description					atultatke	a
* -------------		-----------------------------------------------------------
* n/a
*
* ERRORS USED		Description
* -------------		-----------------------------------------------------
* n/a
*
* RETURN VALUE
* Value    			Description					
* --------------	------------------------------------------------------
* 
* select * from Stg_IE_AgrBudget_Ctl 
* select * from Stg_IE_AgrBudgetInfo_Ctl 
***************************************************************************/
CREATE PROCEDURE [dbo].[MapBudgetFeed]
AS
BEGIN
	
	DECLARE @agrBudgetContainerViewIdSeed int
	DECLARE @agrBudgetIdSeed int
	DECLARE	@sql	varchar(1000)
	DECLARE @agrBudgetICRateIdSeed int
	DECLARE @agrBudgetItemIdSeed int
	DECLARE @agrBudgetContainerIdSeed int
	SET NOCOUNT ON

	-- >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	-- G E T  E X I S T I N G  A G R E E M E N T  I D
	-- >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

	Update Stg_IE_Existing_Agreement
	SET
		AgrAgreementId = Id
	FROM 
		Stg_IE_Existing_Agreement  SEA
		inner join AgrAgreement a on a.FolderNumber = SEA.sFolderNumber 
		and a.documentnumber = (SELECT max(a1.documentNumber) FROM AgrAgreement a1
							WHERE a1.foldernumber = a.foldernumber 																
							and a1.isAmendment = 0 and a1.IsCurrent=1)		

	-- >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	-- B U D G E T  H E A D E R	
	-- >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

	-- >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	-- ADJUST AWARD TYPE
	-- In InfoEd there are three types of budgets Initial, Funding Increment and Adjustment
	-- Initial is assigned to the first budget year and Funding Increment is assigned to years 
	-- following first year. Both these types come to Insight as Annual. So we need to
	-- change all Funding Increment into Initial. We will do that in Insight_Awd_Type field
	-- and keep Orig_Awd_Type with original value. select * from Stg_IE_AgrBudget_Ctl 
	-- >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

	UPDATE Stg_IE_AgrBudget_Ctl 
	SET
		Insight_Awd_Type = 'Annual'
	WHERE
		Insight_Awd_Type = 'Funding Increment' 
		or Insight_Awd_Type = 'Initial'

	UPDATE Stg_IE_AgrBudget_Ctl
	SET
		Insight_Awd_Type = 'Annual'
	WHERE
		Insight_Awd_Type is NULL
		--and BudgetView = 'Pending'
		
	-- >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	-- ADJUST FolderNumber
	--Remove dashes from Folder numbers.
	-- >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	
	UPDATE Stg_IE_AgrBudget_Ctl  
	SET 
		FolderNumber = (Replace(FolderNumber, '-', '')) 
	WHERE 
		foldernumber like '%-%'
	
	-- >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	-- ADJUST BUDGET VIEW, IsAwarded flag
	-- If Budget is Committed then in the feed IsAwarded is coming as 0
	-- and BudgetView is coming as Fully Executed/Awarded.
	-- We need to change IsAwarded to 1, BudgetView to Committed.
	-- Committed is a new BudgetView type in Insight.
	-- >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	UPDATE Stg_IE_AgrBudget_Ctl  
	SET 
		IsAwarded = 1,
		BudgetView = 'Committed'
	WHERE 
		sStatus = 'Committed'


	-- >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	-- S E L E C T  A L L  R E Q U I R E D  F I E L D S  I N T O
	-- T E M P  T A B L E
	-- >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	SELECT 
		SAB.nBudgetId as nBudgetId, 
		SAB.FolderNumber as FolderNumber, 
		a.Id as AgrAgreementId,
		a.AgrBudgetContainerId as AgrBudgetContainerId,
		ABT.Id as AgrBudgetTypeId,
		BVT.Id as AgrBudgetViewTypeId,
		AFM.Id as AgrFundAgreeMapId,
		Datediff(m,ISNULL(SAB.AgrBudgetStartDate, 0),ISNULL(SAB.AgrBudgetEndDate, 0)) as CalculatedMonths,
		isnull(SAB.ICRate2,SAB.ICRate1) as ICRate2,		
		AF.Id as AgrFundId,
		coalesce(SAB.AgrBudgetStartDate,A.ProjectStartDate,'1/1/1900') as AgrBudgetStartDate,
		coalesce(SAB.AgrBudgetEndDate,A.ProjectEndDate,'12/31/2099') as AgrBudgetEndDate		
	INTO #AgrBudgetHeader
	FROM 
		Stg_IE_AgrBudget_Ctl  SAB
		inner join AgrAgreement a on a.FolderNumber = SAB.FolderNumber 
		and a.documentnumber = (SELECT max(a1.documentNumber) FROM AgrAgreement a1
							WHERE a1.foldernumber = a.foldernumber 																
							and a1.isAmendment = 0 and a1.IsCurrent=1)
		inner join AgrBudgetViewType BVT ON BVT.Name = SAB.BudgetView		
		Left Outer Join AgrFund AF on AF.FundNumber = SAB.sPSFundNumber
		Left Outer Join AgrFund_AgrAgreement_Map AFM ON AFM.AgrFundId = AF.Id		
		inner join AgrBudgetType ABT ON ABT.Name = SAB.Insight_Awd_Type
		--Left Outer Join AgrSubcontractor ASUB ON ASUB.InfoEdSubcontractorID = SAB.nSubContractorId
	

		
	UPDATE SAB 
	Set
		AgrSubContractorID = ASUB.Id
	FROM
		Stg_IE_AgrBudget_Ctl SAB 		
		inner join AgrSubcontractor ASUB ON ASUB.InfoEdInstCode = SAB.nSubContractorId
	WHERE
		SAB.nSubContractorId is not null
		


	/*
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	M A P  I D S
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	*/
 
	UPDATE Stg_IE_AgrBudget_Ctl  
	SET 
		AgrAgreementId = ABH.AgrAgreementId,
		AgrBudgetTypeId = ABH.AgrBudgetTypeId,		
		AgrFundAgrAgreementMapId = ABH.AgrFundAgreeMapId,
		AgrBudgetContainerId = ABH.AgrBudgetContainerId,
		AgrBudgetViewTypeId = ABH.AgrBudgetViewTypeId,		
		AgrBudgetStartDate = ABH.AgrBudgetStartDate,
		AgrBudgetEndDate = ABH.AgrBudgetEndDate,
		IsNewBudget = 1,	
		IsValid = 1
	FROM
		Stg_IE_AgrBudget_Ctl  SAB,
		#AgrBudgetHeader ABH 
	WHERE
		ABH.nBudgetId = SAB.nBudgetId 
	

	UPDATE 
		Stg_IE_AgrBudget_Ctl  
	SET 
		IsNewSubContractor = 1 --CASE WHEN SAB.nSubContractorId is not null THEN 1 ELSE NULL
	FROM
		Stg_IE_AgrBudget_Ctl SAB
	WHERE
		nSubContractorId is not null
		and AgrSubContractorId is not null -- They should be matched otherwise we can not insert them.

	

	

	/*
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	E X I S T I N G  B U D G E T  H E A D E R  R E C O R D S
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	*/

	UPDATE Stg_IE_AgrBudget_Ctl  
	SET 
		IsNewBudget = 0,
		AgrBudgetContainerViewId = ABCV.Id,
		AgrBudgetId = AB.Id
	FROM 
		Stg_IE_AgrBudget_Ctl  SAB
		inner join AgrAgreement a on a.FolderNumber = SAB.FolderNumber 
		and a.documentnumber = (SELECT max(a1.documentNumber) FROM AgrAgreement a1
							WHERE a1.foldernumber = a.foldernumber 																
							and a1.isAmendment = 0 and a1.IsCurrent=1)
		inner join  AgrBudgetContainer ABC ON ABC.Id = a.AgrBudgetContainerId
		inner join  AgrBudgetContainerView ABCV ON ABCV.AgrBudgetContainerId = SAB.AgrBudgetContainerId
											and ABCV.AgrBudgetViewTypeId = SAB.AgrBudgetViewTypeId
		inner join  AgrBudget AB ON AB.AgrBudgetContainerViewId = ABCV.Id
									and AB.Year = SAB.Year	
									and AB.AgrBudgetTypeID = SAB.AgrBudgetTypeID

	/*
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	D E T E C T  E R R O R S
	Look for stuff that does not map
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	*/

	UPDATE	Stg_IE_AgrBudget_Ctl  
	SET		IsValid = 0
	WHERE
		   isNull(nBudgetId,'') = ''
		or isNull(FolderNumber,'') = '' 
		or isNull(AgrAgreementId,0) = 0 
		or isNull(Year,0) = 0
		or AgrBudgetStartDate is null
		or AgrBudgetEndDate is null
		or isNull(AgrBudgetContainerId,0) = 0			
		or isNull(AgrBudgetTypeId,0) = 0		


	/*
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	P R E P A R E  F O R  A G R B U D G E T C O N T A I N E R V I E W  T A B L E
	F O R  N O N S U B C O N T R A C T O R
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	*/
	--Get all distinct ContainerIds and View types
	SELECT DISTINCT 
		AgrBudgetContainerId, 
		AgrBudgetViewTypeId
	INTO 
		#DistBudgetContainerView
	FROM
		stg_IE_AgrBudget_Ctl
	WHERE
		IsValid = 1 
		and IsNewBudget = 1
		and nSubContractorId is null
	/*
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	S E E D  I D S F O R C O N T A I N E R  V I E W
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	*/
	--AgrBudgetContainerViewId for Non SubContractor
	IF (SELECT Count(Id) FROM AgrBudgetContainerView) = 0
		SET	@agrBudgetContainerViewIdSeed = 1
	ELSE
		SET	@agrBudgetContainerViewIdSeed = IDENT_CURRENT('AgrBudgetContainerView') + 1
	

	
	IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'tmpSeededAgrBudgetContainerViewIDs')
		DROP TABLE tmpSeededAgrBudgetContainerViewIDs
	
	
	SET @sql = 'SELECT IDENTITY(int, ' + CAST(@agrBudgetContainerViewIdSeed AS varchar) + ', 1) AS AgrBudgetContainerViewId, AgrBudgetContainerId, AgrBudgetViewTypeId INTO tmpSeededAgrBudgetContainerViewIDs FROM #DistBudgetContainerView'
	EXEC(@sql)
	
	IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'tmpSeededAgrBudgetContainerViewIDs') 
	Begin
		UPDATE	SAB
		SET		SAB.AgrBudgetContainerViewId = T.AgrBudgetContainerViewID
		FROM	Stg_IE_AgrBudget_Ctl SAB
				inner join tmpSeededAgrBudgetContainerViewIDs T 
									on T.AgrBudgetContainerId = SAB.AgrBudgetContainerId
									and T.AgrBudgetViewTypeId = SAB.AgrBudgetViewTypeId
		WHERE	nSubContractorId is null
		DROP TABLE dbo.tmpSeededAgrBudgetContainerViewIDs
	End

	DROP TABLE #DistBudgetContainerView

	SELECT	distinct AgrBudgetContainerViewId as AgrBudgetContainerViewId, 			
			Max(Year)as Year			
	INTO	#DistBudgetContainerviewYear
	FROM	stg_IE_AgrBudget_Ctl
	WHERE	
			IsValid = 1 
			and IsNewBudget = 1
			and nSubContractorId is null
	GROUP BY AgrBudgetContainerViewId

	--Get the distinct AgrBudgetContainerViewId field
	INSERT INTO	Stg_IE_AgrBudgetContainerView_Ctl			
			(AgrBudgetContainerViewId, 
			AgrBudgetContainerId,
			AgrBudgetViewTypeId, 
			TargetPatientNumber,
			PerCapitaValue, 
			InflationRate,
			Year)
	SELECT	distinct
			SAB.AgrBudgetContainerViewId,
			max(SAB.AgrBudgetContainerId), 
			max(SAB.AgrBudgetViewTypeId), 
			max(SAB.TargetPatientNumber),
			max(SAB.PerCapitaValue),
			max(SAB.InflationRate),
			max(SAB.Year)
	FROM 
			stg_IE_AgrBudget_Ctl SAB
			inner join #DistBudgetContainerviewYear DBCY 
								on DBCY.AgrBudgetContainerViewId = SAB.AgrBudgetContainerViewId
								and DBCY.Year	= SAB.Year
	
	GROUP BY SAB.AgrBudgetContainerViewId

	DROP TABLE #DistBudgetContainerviewYear

	
	/*
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	S E E D  I D S  F O R  A G R B U D G E T
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	*/
	--AgrBudgetId
	IF (SELECT Count(Id) FROM AgrBudget) = 0
		SET	@agrBudgetIdSeed = 1
	ELSE
		SET	@agrBudgetIdSeed = IDENT_CURRENT('AgrBudget') + 1

	
	IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'tmpSeededAgrBudgetIDs')
		DROP TABLE tmpSeededAgrBudgetIDs

	SET	@sql = 'SELECT	IDENTITY(int, ' + CAST(@agrBudgetIdSeed AS varchar) + ', 1) AS AgrBudgetId, nBudgetId INTO tmpSeededAgrBudgetIDs FROM Stg_IE_AgrBudget_Ctl  where IsNewBudget = 1 and IsValid = 1'
	EXEC(@sql)
	

	IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'tmpSeededAgrBudgetIDs') 
	Begin
		UPDATE	Stg_IE_AgrBudget_Ctl 
		SET		AgrBudgetId = tmpSeededAgrBudgetIDs.AgrBudgetId
		FROM	tmpSeededAgrBudgetIDs
		WHERE	Stg_IE_AgrBudget_Ctl.nBudgetId = tmpSeededAgrBudgetIDs.nBudgetId
		
		DROP TABLE dbo.tmpSeededAgrBudgetIDs
	End


	/*
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	A G R B U D G E T I C R A T E  R E C O R D S
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	*/
	--Take care of 1st rate record
	INSERT INTO
		Stg_IE_AgrBudgetICRate
		(AgrBudgetICRateId, nBudgetId,
		AgrBudgetId, Rate,
		NumberOfMonths, SequenceNo,
		EffectiveDate, IsValid,
		IsNewRecord)	
	SELECT
		NULL as AgrBudgetICRateId,
		nBudgetId as nBudgetId,
		AgrBudgetId as AgrBudgetId,
		ICRate1 as Rate,
		MonthsRate as NumberOfMonths,
		1 as SequenceNo,
		NULL as EffectiveDate,
		IsValid as IsValid,
		1 as IsNewRecord
	FROM
		Stg_IE_AgrBudget_Ctl 
	
	--Now take care of 2nd rate if Budget months is greater than MonthsRate which is coming from Header feed.
	INSERT INTO
		Stg_IE_AgrBudgetICRate
		(AgrBudgetICRateId, nBudgetId,
		AgrBudgetId, Rate,
		NumberOfMonths, SequenceNo,
		EffectiveDate, IsValid,
		IsNewRecord)	
	SELECT
		NULL as AgrBudgetICRateId,
		nBudgetId as nBudgetId,
		AgrBudgetId as AgrBudgetId,
		ICRate2 as Rate,
		(DATEDIFF(MONTH, SAB.AgrBudgetStartDate,SAB.AgrBudgetEndDate) - MonthsRate) as NumberOfMonths,
		2 as SequenceNo,
		NULL as EffectiveDate,
		IsValid as IsValid,
		1 as IsNewRecord
	FROM
		Stg_IE_AgrBudget_Ctl  SAB
	WHERE
		(DATEDIFF(MONTH, SAB.AgrBudgetStartDate,SAB.AgrBudgetEndDate) - MonthsRate) > 0 
		and SAB.IsValid = 1  --Take only valid records
		--AND SAB.ICRate1 > 0 Do we need this? There are some ICRate1 that is coming 0. Do we need to create AgrBudgetICRate record for 0?


	/*
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	D E T E C T  E R R O R S
	Look for stuff that does not map
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	*/
	UPDATE	Stg_IE_AgrBudgetICRate  
	SET		IsValid = 0
	WHERE
		   isNull(nBudgetId,'') = ''		
		or isNull(AgrBudgetId,0) = 0 
		
	-- >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	-- B U D G E T  D E T A I L	
	-- >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	
	-- >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	-- G E T  A L L  I D S
	-- >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	
	UPDATE Stg_IE_AgrBudgetInfo_Ctl  
	SET 
		AgrBudgetId = SAB.AgrBudgetId,
		IsValid = SAB.IsValid,
		IsNewRecord = 1
	FROM
		Stg_IE_AgrBudgetInfo_Ctl  SABD
		inner join Stg_IE_AgrBudget_Ctl  SAB ON SABD.nBudgetId = SAB.nBudgetId
		
	
	--AgrContainerAccountTemplateMapId and FinAccountId

	UPDATE Stg_IE_AgrBudgetInfo_Ctl  
	SET 
		AgrContainerAccountTemplateMapId = ACTM.Id,
		FinAccountId = FA.Id
	FROM
		Stg_IE_AgrBudgetInfo_Ctl  SABI
		inner join FinAccount FA ON FA.Number = SABI.PSAccountNumber
		inner join AgrBudgetItemAccount_Template ABIT ON ABIT.FinAccountId = FA.ID
		inner join AgrBudgetItem_ContainerAccount_Template_Map ACTM ON ACTM.AgrAccountTemplateId = ABIT.Id

	
	/*
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	D E T E C T  E R R O R S
	Look for stuff that does not map
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	*/ 
	--select * from Stg_IE_AgrBudgetInfo_Ctl
	UPDATE	Stg_IE_AgrBudgetInfo_Ctl  
	SET		IsValid = 0
	WHERE
		   isNull(nBudgetDetailId,'') = ''
		or isNull(nBudgetId,'') = ''
		or isNull(AgrBudgetId,0) = 0 
		or isNull(PSAccountNumber,0) = 0 								
		or isNull(AgrContainerAccountTemplateMapId,0) = 0
		or isNull(FinAccountId,0) = 0
		
	
	
	DROP TABLE #AgrBudgetHeader

	-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	--S U B C O N T R A C T
	-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

	/********************************************************************/
	/*Take care of New Budget Container for SubContractor records		*/

	UPDATE 
		Stg_IE_AgrBudget_Ctl  
	SET 
		AgrBudgetContainerId = null,
		isValid = 1
	WHERE
		nSubContractorId is not null


	--Create New AgrBudgetContainer 
	SELECT 
		distinct SAB.AgrAgreementId, SAB.AgrSubContractorId, SABI.FinAccountId
	INTO
		#DistSubContractor --tempSubContractor --
	FROM
		Stg_IE_AgrBudget_Ctl SAB
		inner join Stg_IE_AgrBudgetInfo_Ctl SABI on SABI.nBudgetId = SAB.nBudgetId
	WHERE
		SAB.IsValid = 1
		and SABI.IsValid = 1 
		--and IsNewBudget = 1
		and IsNewSubContractor = 1


	/*
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	S E E D  I D S F O R  A G R B U D G E T C O N T A I N E R 
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	*/
	IF (SELECT Count(Id) FROM AgrBudgetContainer) = 0
		SET	@agrBudgetContainerIdSeed = 1
	ELSE
		SET	@agrBudgetContainerIdSeed = IDENT_CURRENT('AgrBudgetContainer') + 1
	


	IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'tmpSeededAgrBudgetContainerIDs')
		DROP TABLE tmpSeededAgrBudgetContainerIDs

	
	SET @sql = 'SELECT IDENTITY(int, ' + CAST(@agrBudgetContainerIdSeed AS varchar) + ', 1) AS AgrBudgetContainerId, AgrAgreementId, FinAccountId, AgrSubContractorId INTO tmpSeededAgrBudgetContainerIDs FROM #DistSubContractor'
	EXEC(@sql)
	

	IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'tmpSeededAgrBudgetContainerIDs') 
	Begin
		INSERT INTO	Stg_IE_AgrBudgetContainer_Ctl
			(AgrBudgetContainerId, 	
			[Name], 
			Description,
			AgrAgreementId, 
			FinAccountId,
			AgrSubContractorId,
			IndirectCostBaseId,
			AgrBudgetTemplateTypeId)
		SELECT
			AgrBudgetContainerId,
			'SubContractor Budget Container: ' + Cast(AgrSubContractorId AS varchar(10)),
			'SubContractor budget Container for ' + Cast(AgrSubContractorId AS varchar(10)),
			AgrAgreementId, 
			FinAccountId,
			AgrSubContractorId,
			null,
			2		
		FROM
			tmpSeededAgrBudgetContainerIDs

		DROP TABLE dbo.tmpSeededAgrBudgetContainerIDs
	End


	DROP TABLE #DistSubContractor



	SELECT	SAB.AgrBudgetContainerId,SAB.AgrAgreementId, SAB.nBudgetId,
		SAB.AgrSubContractorID, SABC.FinAccountId 
	INTO 
		#SubContractorContainer1
	FROM
		Stg_IE_AgrBudget_Ctl SAB
		--inner join Stg_IE_AgrBudgetInfo_Ctl SABI on SABI.nBudgetId = SAB.nBudgetID
													--and SABI.FinAccountId = SABC.FinAccountId	
												
		inner join Stg_IE_AgrBudgetContainer_Ctl SABC on SABC.AgrAgreementId = SAB.AgrAgreementId
													and  SABC.AgrSubContractorID = SAB.AgrSubContractorID
	WHERE
		SAB.IsValid = 1 		
		and SAB.IsNewSubContractor = 1

	SELECT 
		ABC.AgrBudgetContainerId,SCC.AgrAgreementId, SCC.nBudgetId,
		SCC.AgrSubContractorID, SCC.FinAccountId
	INTO
		#SubContractorContainer2
	FROM 
		#SubContractorContainer1 SCC
		inner join Stg_IE_AgrBudgetContainer_Ctl ABC on ABC.AgrAgreementID = SCC.AgrAgreementId
											and ABC.AgrSubContractorId = SCC.AgrSubContractorID
											and ABC.FinAccountId = SCC.FinAccountId

	UPDATE
		SAB
	SET
		SAB.AgrBudgetContainerId = SCC.AgrBudgetContainerId
	FROM
		Stg_IE_AgrBudget_Ctl SAB
		inner join #SubContractorContainer2 SCC on SCC.nBudgetId = SAB.nBudgetId
	
	DROP TABLE #SubContractorContainer1	
	DROP TABLE #SubContractorContainer2
	

	/*
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	P R E P A R E  F O R  A G R B U D G E T C O N T A I N E R V I E W  T A B L E
	F O R S U B C O N T R A C T O R
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	*/
	--Get all distinct ContainerIds and View types
	SELECT DISTINCT 
		AgrBudgetContainerId, 
		AgrBudgetViewTypeId
	INTO 
		#DistBudgetContainerViewSubCon
	FROM
		stg_IE_AgrBudget_Ctl
	WHERE
		IsValid = 1 
		and IsNewBudget = 1
		and nSubContractorId is not null
	/*
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	S E E D  I D S
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	*/
	--AgrBudgetContainerViewId for Non SubContractor
	/*IF (SELECT Count(Id) FROM AgrBudgetContainerView) = 0
		SET	@agrBudgetContainerViewIdSeed = 1
	ELSE
		SET	@agrBudgetContainerViewIdSeed = IDENT_CURRENT('AgrBudgetContainerView') + 1
	*/

	SELECT @agrBudgetContainerViewIdSeed  = max(AgrBudgetContainerViewId) + 1 from Stg_IE_AgrBudgetContainerView_Ctl

	IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'tmpSeededAgrBudgetContainerViewIDs')
		DROP TABLE tmpSeededAgrBudgetContainerViewIDs
	
	
	SET @sql = 'SELECT IDENTITY(int, ' + CAST(@agrBudgetContainerViewIdSeed AS varchar) + ', 1) AS AgrBudgetContainerViewId, AgrBudgetContainerId, AgrBudgetViewTypeId INTO tmpSeededAgrBudgetContainerViewIDs FROM #DistBudgetContainerViewSubCon'
	EXEC(@sql)
	
	IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'tmpSeededAgrBudgetContainerViewIDs') 
	Begin
		UPDATE	SAB
		SET		SAB.AgrBudgetContainerViewId = T.AgrBudgetContainerViewID
		FROM	Stg_IE_AgrBudget_Ctl SAB
				inner join tmpSeededAgrBudgetContainerViewIDs T 
									on T.AgrBudgetContainerId = SAB.AgrBudgetContainerId
									and T.AgrBudgetViewTypeId = SAB.AgrBudgetViewTypeId
		WHERE	nSubContractorId is not null
		DROP TABLE dbo.tmpSeededAgrBudgetContainerViewIDs
	End

	DROP TABLE #DistBudgetContainerViewSubCon

	SELECT	distinct AgrBudgetContainerViewId as AgrBudgetContainerViewId, 			
			Max(Year)as Year			
	INTO	#DistBudgetContainerviewYearSubCon
	FROM	stg_IE_AgrBudget_Ctl
	WHERE	
			IsValid = 1 
			and IsNewBudget = 1
			and nSubContractorId is not null
	GROUP BY AgrBudgetContainerViewId

	--Get the distinct AgrBudgetContainerViewId field
	INSERT INTO	Stg_IE_AgrBudgetContainerView_Ctl			
			(AgrBudgetContainerViewId, 
			AgrBudgetContainerId,
			AgrBudgetViewTypeId, 
			TargetPatientNumber,
			PerCapitaValue, 
			InflationRate,
			Year)
	SELECT	distinct
			SAB.AgrBudgetContainerViewId,
			max(SAB.AgrBudgetContainerId), 
			max(SAB.AgrBudgetViewTypeId), 
			max(SAB.TargetPatientNumber),
			max(SAB.PerCapitaValue),
			max(SAB.InflationRate),
			max(SAB.Year)
	FROM 
			stg_IE_AgrBudget_Ctl SAB
			inner join #DistBudgetContainerviewYearSubCon DBCY 
								on DBCY.AgrBudgetContainerViewId = SAB.AgrBudgetContainerViewId
								and DBCY.Year	= SAB.Year
	
	GROUP BY SAB.AgrBudgetContainerViewId

	DROP TABLE #DistBudgetContainerviewYearSubCon


	-- >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	-- A G R E E M E N T  S U B C O N T R A C T O R  M A P	
	-- >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>	

	INSERT INTO
		Stg_IE_AgrAgreementSubcontractor_Map
		(AgrAgreementSubConMapId, AgrAgreementId,
		AgrSubContractorId, AgrBudgetContainerId,
		FinAccountId, IsNewSubContractor,
		IsValid)
	SELECT
		null as AgrAgreementSubConMapId,
		SABC.AgrAgreementId as AgrAgreementId,
		SABC.AgrSubContractorId as AgrSubContractorId,
		SABC.AgrBudgetContainerId as AgrBudgetContainerId, 
		SABC.FinAccountId as FinAccountId,
		1 as IsNewSubContractor,
		1 as IsValid
	FROM
		Stg_IE_AgrBudgetContainer_Ctl  SABC
		

	/*
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	D E T E C T  E R R O R S
	Look for stuff that does not map
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	*/

	UPDATE	Stg_IE_AgrBudget_Ctl  
	SET		IsValid = 0
	WHERE
		   isNull(nBudgetId,'') = ''
		or isNull(FolderNumber,'') = '' 
		or isNull(AgrAgreementId,0) = 0 
		or isNull(Year,0) = 0
		or AgrBudgetStartDate is null
		or AgrBudgetEndDate is null
		or isNull(AgrBudgetContainerId,0) = 0			
		or isNull(AgrBudgetTypeId,0) = 0
		
	
	SET NOCOUNT OFF

END


GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Creating [dbo].[IE_Stg_IE_SvcEntityStaffedPerson_Ctl_Lookup]'
GO

CREATE PROCEDURE dbo.IE_Stg_IE_SvcEntityStaffedPerson_Ctl_Lookup 
AS
BEGIN

	SET NOCOUNT ON;


	-- first, insert any staff person roles that don't already exist
	SELECT DISTINCT	LTRIM(RTRIM(s.sRole)) AS sRole
	INTO			#tmp1
	FROM			Stg_IE_SvcEntityStaffedPerson_Ctl s
	LEFT OUTER JOIN	AdmStaffedPersonType t
		ON				LTRIM(RTRIM(s.sRole)) = LTRIM(RTRIM(t.[Name]))
	WHERE			t.[Id] IS NULL

	IF (@@ROWCOUNT > 0)
	BEGIN
		INSERT	AdmStaffedPersonType
				(
					[Name], [Description], RexName, IsSiteResponsible
				)
		SELECT	sRole, sRole, sRole, 0
		FROM	#tmp1
	END

	-- temp table is created even if no rows were inserted, so drop it
	DROP TABLE #tmp1

	-- now, look up some type data
	UPDATE	Stg_IE_SvcEntityStaffedPerson_Ctl
	SET		AdmStaffedPersonTypeId = AdmStaffedPersonType.[Id]
	FROM	AdmStaffedPersonType
	WHERE	LTRIM(RTRIM(Stg_IE_SvcEntityStaffedPerson_Ctl.sRole)) = LTRIM(RTRIM(AdmStaffedPersonType.[Name]))

	UPDATE	Stg_IE_SvcEntityStaffedPerson_Ctl
	SET		AgrBudgetViewTypeId = AgrBudgetViewType.[Id]
	FROM	AgrBudgetViewType
--	WHERE	LTRIM(RTRIM(Stg_IE_SvcEntityStaffedPerson_Ctl.sEffortView)) = LTRIM(RTRIM(AgrBudgetViewType.[Name]))
	WHERE	LTRIM(RTRIM(Stg_IE_SvcEntityStaffedPerson_Ctl.sBudgetView)) = LTRIM(RTRIM(AgrBudgetViewType.[Name]))

	-- look for SvcEntityId
	UPDATE STG 
	SET STG.SvcEntityId = A.SvcEntityId
	FROM Stg_IE_SvcEntityStaffedPerson_Ctl STG JOIN AgrAgreement A
	--	ON STG.prop_no = A.PropNumber
	--and A.Id = (select max(id) from AgrAgreement ag1 where ag1.PropNumber = A.PropNumber)
	ON STG.FolderNumber = A.FolderNumber
	and A.Id = (select max(id) from AgrAgreement ag1 where ag1.FolderNumber = A.FolderNumber)

	-- look for AdmPersonId
	UPDATE STG 
	SET STG.AdmPersonId = AP.Id
	FROM Stg_IE_SvcEntityStaffedPerson_Ctl STG JOIN FwkDomainUser DU
		ON STG.sUserName = DU.Username
	JOIN AdmPerson AP 
		ON DU.Id = AP.FwkDomainUserId

	-- delete any records for which either of these IDs was not found
	DELETE	Stg_IE_SvcEntityStaffedPerson_Ctl
	WHERE	SvcEntityId IS NULL
	OR		AdmStaffedPersonTypeId IS NULL
	OR		AgrBudgetViewTypeId IS NULL
	OR		AdmPersonId IS NULL
END

GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Altering [dbo].[MapStagedAgreementsFromInfoEd]'
GO



/***************************************************************************
* Name:			MapStagedAgreementsFromInfoEd
* Purpose:		Update Type ID columns (both new and existing) to the Insight 
*				type IDs on the Staging table Stg_IE_AgrAGreement based on 
*				the data coming over from IE.
*
***************************************************************************/
ALTER PROCEDURE dbo.MapStagedAgreementsFromInfoEd
AS
BEGIN

	SET NOCOUNT ON

	-- Strip out any junk characters from the FolderNumber (
	-- the CompleteFolderNumber field holds the subprojects
	Update Stg_IE_AgrAGreement set FolderNumber = Replace (FolderNumber, '-', '')

	-- Mark the records that have multiple document numbers
	Update Stg_IE_AgrAGreement set HasMultipleDocs = 1 where FolderNumber in 
		(select distinct(folderNUmber) from Stg_IE_AgrAgreement
		Group By FolderNumber
		having count(FolderNumber) > 1)

	-- Populate current the PersonIds via the username.
	Update S 
	set PIPersonId = A.Id
	from Stg_IE_AgrAgreement S
	inner join FwkDomainUser U
		on U.UserName = S.PIUserName
	inner join AdmPerson A
		on A.FwkDomainUserId = U.Id

	-- FacultyId Match
	Update S set PIPersonId = Map.AdmPersonId
		From Stg_IE_AgrAgreement S
		inner join AdmPerson_InfoEdFaculty_Map Map
			On Map.Unique_Id = S.PIFacultyId
		Where S.PIPersonId is NULL
	
	-- Agreement Status Type
	Update S set AgrAgreementStatusTypeId = Sub.Id
		From Stg_IE_AgrAgreement S
		inner join AgrAgreementStatusType Sub
			on Sub.[Name] = S.OverallStatus
	
	-- AgrTransactionType
	Update S set AgrTransactionTypeId = Sub.Id
		FROM Stg_IE_AgrAgreement S
		inner join AgrTransactionType Sub
			on Sub.[Name] = S.TransactionType	


	-- Agreement Type.
	Update S set AgrAgreementTypeId = Sub.Id
		From Stg_IE_AgrAgreement S
		inner join AgrAgreementType Sub
			on Sub.[Name] = S.AgreementType
	

	-- Set the Agreemetn Type to Undefined for any that are still NULL
	Update Stg_IE_AgrAgreement set AgrAgreementTypeId = AgrType.Id
		From AgrAgreementType AgrType
		WHERE (Stg_IE_AgrAgreement.AgreementType IS NULL OR Stg_IE_AgrAgreement.AgreementType = '')
			and Stg_IE_AgrAgreement.AgrAgreementTypeId IS NULL
			and AgrType.[Name] = 'Undefined'

	-- AgrAgreementId
	Update Stg_IE_AgrAgreement set AgrAgreementId = Sub.AgrAgreementId 
		from 
		(select A.Id as AgrAgreementId, A.PropNumber from AgrAgreement A
			inner join Stg_IE_AgrAgreement S
				on A.PropNumber = S.Prop_No ) Sub
		Where Stg_IE_AgrAgreement.Prop_No = Sub.PropNumber

	-- MAP VALUES INSERTED FROM KEN'S PEOPLESOFT FEED THAT MIGHT ALREADY BE THERE
	-- BASED UPON THE FOLDER NUMBER (SINCE THOSE WILL BE CONSISTENT). 
	Update S set AgrAgreementId = A.Id
	From Stg_IE_AgrAgreement S
	inner join AgrAgreement A
		on A.FolderNumber = S.FolderNumber
	WHERE S.AgrAgreementId is null and A.IsCurrent = 1 and A.IsAmendment = 0
		

	-- Update existing values
	Update Stg_IE_AgrAgreement set	SvcEntityId = AgrAgreement.SvcEntityId,	
									FwkResourceId = AgrAgreement.FwkResourceId,
									AgrBudgetContainerId = AgrAgreement.AgrBudgetContainerId,
									AnnAnnotationContainerId = AgrAgreement.AnnAnnotationContainerId,
									ExistingPIPersonId = AgrAgreement.PIPersonId,
									ExistingProjectStartDate = AgrAgreement.ProjectStartDate,
									ExistingProjectEndDate = AgrAgreement.ProjectEndDate,
									ExistingReceivedDate = AgrAgreement.ReceivedDate,
									ExistingLegacyIdentifier = AgrAgreement.LegacyIdentifier,
									ExistinParentFolderNumber = AgrAgreement.ParentFolderNumber,
									ExistingAgreementTitle = CAST(AgrAgreement.Title as Varchar(4000)),
									ExistingAgreementShortTitle = AgrAgreement.ShortTitle,
									ExistingRFAID = AgrAgreement.RFAId,
									ExistingRFATitle = AgrAgreement.RFATitle,
									ExistingAgreementTypeId = AgrAgreement.AgrAgreementTypeId,
									ExistingAgrAgreementStatusTypeId = AgrAgreement.AgrAgreementStatusTypeId,
									ExistingDocumentNumber = AgrAgreement.DocumentNumber,
									ExistingProp_No	= AgrAgreement.PropNumber
		from AgrAgreement 
		where Stg_IE_AgrAgreement.AgrAgreementId = AgrAgreement.Id


	-- Existing PIPerson Usernames.
	Update Stg_IE_AgrAgreement set ExistingPIUserName = SubString(FwkDomainUser.UserName, 0, 10)
		From FwkDomainUser
			inner join AdmPerson Per
				on Per.FwkDomainUserId = FwkDomainUser.Id
			inner join AgrAgreement 
				on Per.Id = AgrAgreement.PIPersonId
		WHERE Stg_IE_AgrAgreement.AGrAGreementId = AgrAgreement.Id


	-- Existing Status
	Update Stg_IE_AgrAgreement set ExistingStatus = AgrAgreementStatusType.[Name]
		From AgrAgreementStatusType 
		inner join AgrAgreement 
			on AgrAgreement.AgrAgreementStatusTypeId = AgrAgreementStatusType.Id
		WHERE AgrAgreement.id = Stg_IE_AgrAgreement.AGrAGreementId

	-- Existing ACtivityType
	Update Stg_IE_AgrAgreement set ExistingActivityType = AgrActivityType.[Description]
		From AgrActivityType 
		inner join AgrActivity 
			on AgrActivity.AgrActivityTypeId = AgrActivityType.Id
		WHERE AgrActivity.AgrAgreementId = Stg_IE_AgrAgreement.AGrAGreementId

	-- Existing TransactionType
	Update Stg_IE_AgrAgreement set ExistingTransactionType = AgrTransactionType.[Name]
		From AgrTransactionType 
		inner join AgrAgreement 
			on AgrAgreement.AgrTransactionTypeId = AgrTransactionType.Id
		WHERE AgrAgreement.id = Stg_IE_AgrAgreement.AGrAGreementId

	-- Existing Sponsor		
	Update Stg_IE_AgrAgreement set ExistingAdmSponsorId = Map.AdmSponsorId,
								   ExistingSpon_Code = S.InfoEdSponCode
		From AgrAgreement Agr
		inner join SvcEntity_AdmSponsor_Map Map
			on Map.SvcEntityId = Agr.SvcEntityId
		inner join AdmSponsor S
			on Map.AdmSponsorId = S.Id
		Where Stg_IE_AgrAgreement.AgrAgreementId = Agr.Id
		and Map.AdmSponsorRelationTypeId = 1

	-- new Sponsor
	Update Stg_IE_AgrAgreement set AdmSponsorId = S.Id
		From AdmSponsor S
		where S.InfoEdSponCode = Stg_IE_AgrAgreement.Spon_Code


	-- AGRAgreementType Id (from IE)
	Update Stg_IE_AgrAgreement set AgrAgreementTypeId = AT.Id
		From AgrAgreementType AT
		where AT.[Name] = Stg_IE_AgrAgreement.NewAgreementType

	-- Existing Agreement Type (text)
	Update Stg_IE_AgrAgreement set ExistingAgreementType = AT.[Name]	
		From AgrAgreementType AT
			inner join AgrAgreement A
				on A.AgrAgreementTypeId = AT.Id
		where Stg_IE_AgrAgreement.AgrAgreementId = A.Id


	-- Set documnet number to 1 for new Agreements
	UPDATE Stg_IE_AgrAgreement SET DocumentNumber = 1
		WHERE AgrAgreementId IS NULL 

	-- Set Document Number to 1 for those records with only one entry in staging, 
	-- since we're bringing everything over.
	UPDATE Stg_IE_AgrAgreement SET DocumentNumber = 1
		WHERE HasMultipleDocs = 0

	-- Add calc here to update the DocumentNumber to the correct value based on 
	-- subprojects, setting the 'Master' record to the highest value
	Update Stg_IE_AgrAgreement set DocumentNumber = substring(CompleteFolderNumber, 13, 2) 
		where HasMultipleDocs = 1  and CompleteFolderNumber not like '%SubProj%' 
				and IsNumeric(substring(CompleteFolderNumber, 13, 2)) = 1

	-- Set document 1 (the Master doc) to be the Current one, since 
	-- that's how it will work with InfoEd.
	UPDATE Stg_IE_AgrAgreement SET IsCurrent = 1
		WHERE DocumentNumber = 1
	
	UPDATE Stg_IE_AgrAgreement SET IsCurrent = 0
		WHERE DocumentNumber != 1

	-- default this to 1, we won't be getting this from InfoEd
	UPDATE Stg_IE_AgrAgreement SET MultipleGrantNumbering = 1
		WHERE MultipleGrantNumbering IS NULL

	-- Set the Activity Type based on what's coming from InfoEd.
	UPDATE S set AgrActivityTypeId = Sub.Id
		From Stg_IE_AgrAgreement S
		inner join AgrActivityType Sub
			on Sub.[Description] = Substring(S.ActivityType, 0, CHARINDEX('(', S.ActivityType))
		WHERE AgrActivityTypeId IS NULL
		and ActivityType IS NOT NULL

	-- set the PS descriptions for the UI.
	UPDATE S set ActTypePSDescription = Sub.Description
		FROM Stg_IE_AgrAgreement S
		inner join ActivityTypePSCode Sub
			ON S.ActPSCode = Sub.PSCode

	SET NOCOUNT OFF

	END



GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Creating [dbo].[GetContractDetails]'
GO

/************************************************************************************************/          
/* Name  :GetContractDetails                                                               */          
/* Purpose :Procedure for getting the contract details            */          
/* PARAMETERS          
* Name       Description               
* -------------   -------------------------------------------          
*  @domainUserId Domain User ID          
*  @agreementId  Agreement ID          
*  @fundNumber   fundnumber for the agreement        
* ERRORS USED   Description          
* -------------   -------------------------------------------          
* n/a          
*          
* RESULT SETs          
---ContractDetails          
          
* RETURN VALUE          
* Value       Description               
* -------------   -----------------------------------------------          
* n/a          
*          
******************************************************************/           
--------------------------------------------------------------------
--Modifications:
--09-04-2007	Performance improvements: introduce (nolock)
--------------------------------------------------------------------
CREATE PROCEDURE [dbo].[GetContractDetails]          
(           
 @domainUserId INTEGER,          
 @agreementId INTEGER,        
 @fundNumber varchar(30)= Null          
)          
AS          
BEGIN          
SET NOCOUNT ON          
 DECLARE @awardedBudget INTEGER           
 DECLARE @budgetTotalLine INTEGER          
 SET @awardedBudget = 3 --Awarded budget          
 SET @budgetTotalLine = 15          
-- >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>          
-- G E T  Sub Contractor   R E S U L T S E T  F O R  U S E R            
-- Return a complete Sub Contractor information resultset from the agreeementId          
-- >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>          
          
SELECT           
  ISNULL(sc.[Name], '') AS 'SubcontractorName'           
 ,sc.[Id]          
 ,ISNULL(SUM(bi.ItemValue),0) AS 'Budget'          
 ,'Active' AS 'Status'-- Here we are taking only subcontractors who are          
        -- mapped to Agreement. So always status as active          
FROM          
        AgrAgreement_Fct af (nolock)         
INNER JOIN          
        AgrAgreement_Subcontractor_map asm (nolock)          
ON          
        asm.agrAgreementId = af.agreementId          
INNER JOIN          
 AgrSubContractor sc (nolock)          
ON          
        sc.[Id] = asm.AgrSubcontractorId          
INNER JOIN          
        AgrBudgetContainer bc (nolock)          
ON          
        bc.[ID] = asm.AgrBudgetContainerId          
INNER JOIN          
        AgrBudgetContainerView bcv (nolock)          
ON          
 bcv.AgrBudgetContainerId = asm.AgrBudgetContainerId          
INNER JOIN          
        AgrBudget b (nolock)          
ON          
        b.AgrBudgetContainerViewId = bcv.[ID]          
INNER JOIN          
        AgrFund_AgrAgreement_Map fam (nolock)          
ON          
        fam.[Id] = b.AgrFundAgreeMapId          
AND  af.agreementId = fam.AgrAgreementId          
INNER JOIN          
         AgrBudgetItem bi (nolock)          
ON          
         bi.AgrBudgetId = b.[ID]          
INNER JOIN          
         AgrBudgetItem_ContainerAccount_Template_Map tm (nolock)          
ON          
         tm.[ID] = bi.AgrContainerAccountTemplateMapId          
WHERE          
         fam.AgrAgreementId = @agreementId          
     AND bcv.AgrBudgetViewTypeId = @awardedBudget --Awarded budget          
     AND tm.AgrAccountTemplateId = @budgetTotalLine -- Budget Total Line          
GROUP BY          
  sc.[Name]           
 ,sc.[Id]          
-- >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>          
-- G E T  Related Protocols    R E S U L T S E T  F O R  U S E R            
-- Return a complete Related Protocols  information resultset from the agreementId          
-- >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>          
SELECT           
  pro.Title          
 ,pro.ShortTitle AS 'Name'          
 ,pro.ProtocolNumber AS 'Number'          
 , ISNULL(agrfct.PILastName,'') + ', ' + ISNULL(agrfct.PIFirstName,'') AS 'PIName'          
 ,CASE WHEN LEN(pro.SubStatusId) > 0 THEN          
   status.[Name] + ', ' + substatus.[Name]           
   ELSE status.[Name]           
  END AS 'OverallStatus'          
--Protocol types are not yet available and currently          
--,there is only have 1 protocol type which is "Human".          
 ,'Human' AS 'Type'           
 , pro.ExpirationDate          
FROM           
 Agreement_Protocol_Relate agrProtocol (nolock)          
INNER JOIN          
 AgrAgreement_fct agrfct (nolock)       
ON          
 agrfct.FolderNumber = agrProtocol.AgreementFolderNumber          
INNER JOIN          
 Protocol pro (nolock)          
ON          
 pro.ProtocolNumber = agrProtocol.ProtocolNumber          
INNER JOIN           
 ProtocolOverallStatusType status (nolock)          
ON          
 pro.overallstatusid = status.[id]          
LEFT OUTER JOIN          
 ProtocolSubStatusType substatus (nolock)          
ON          
 pro.SubStatusId = substatus.[id]          
WHERE           
  agrfct.[ID] =  (SELECT MAX(af1.[ID]) FROM AgrAgreement_fct af1 (nolock)          
                           WHERE af1.FolderNumber  = agrfct.FolderNumber)          
AND           
 pro.DocumentNumber  = (SELECT MAX(p1.DocumentNumber) FROM Protocol p1 (nolock)           
                          WHERE p1.ProtocolNumber = pro.ProtocolNumber          
                          AND p1.IsAmendment = 0 and p1.IsCurrent = 1)           
AND          
 agrfct.AgreementId = @agreementId          
GROUP BY           
pro.Title,          
pro.ShortTitle,          
pro.ProtocolNumber,          
PILastName,          
PIFirstName,          
status.[Name],          
pro.ExpirationDate,          
substatus.[Name],          
pro.SubStatusId          
           
-- >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>          
-- G E T  Associated Agreements     R E S U L T S E T  F O R  U S E R            
-- Return a complete Associated Agreements information resultset from the agreementId          
-- >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>          
 SELECT          
   award.[Description] AS 'Type'          
  ,CASE isnull(status.Name, 'R')          
            WHEN 'A' THEN 'Active'          
   WHEN 'I' THEN 'Inactive'          
   WHEN 'R' THEN 'Pending'          
   END AS 'Status'          
  ,agrfct.Title AS 'ProjectTitle'          
  ,agrfct.ProjectStartDate          
  ,agrfct.ProjectEndDate          
  ,agrfct.BudgetStartDate          
  ,agrfct.BudgetEndDate          
  ,famap.ActivationDate          
  ,CASE isnull(status.Name, 'R')          
   WHEN 'I' THEN famap.EffectiveDate          
   ELSE null          
   END AS 'InactivationDate'          
  ,agrfct.AgreementId          
  ,agrfct.FundNumber          
  ,agrfct.SponsorName          
  ,ISNULL(agrfct.PILastName,'') + ', ' + ISNULL(agrfct.PIFirstName,'') AS 'PIName'          
 FROM          
   dbo.GetAssociatedAgreements(@agreementId)assoagr          
 INNER JOIN          
  AgrAgreement_fct agrfct (nolock)          
 ON          
  agrfct.AgreementId = assoagr.AgreementId          
 INNER JOIN          
  AgrAgreement agreement (nolock)          
 ON          
  agrfct.AgreementId = agreement.[ID]          
 INNER JOIN          
  AgrFundAwardType award (nolock)          
 ON          
  award.[ID] = agreement.AgrAgreementTypeId          
 INNER JOIN          
  AgrFundStatusType status (nolock)          
 ON          
  status.[ID] = agrfct.FundStatusTypeId          
 INNER JOIN          
     AgrFund_AgrAgreement_Map famap (nolock)          
 ON          
     famap.AgrFundId = agrfct.FundId and           
     famap.AgrAgreementId = agrfct.AgreementId    

UNION

   SELECT          
   award.[Description] AS 'Type'          
  ,CASE isnull(status.Name, 'R')          
            WHEN 'A' THEN 'Active'          
   WHEN 'I' THEN 'Inactive'          
   WHEN 'R' THEN 'Pending'          
   END AS 'Status'          
  ,agrfct.Title AS 'ProjectTitle'          
  ,agrfct.ProjectStartDate          
  ,agrfct.ProjectEndDate          
  ,agrfct.BudgetStartDate          
  ,agrfct.BudgetEndDate          
  ,famap.ActivationDate          
  ,CASE isnull(status.Name, 'R')          
   WHEN 'I' THEN famap.EffectiveDate          
   ELSE null          
   END AS 'InactivationDate'          
  ,agrfct.AgreementId          
  ,agrfct.FundNumber          
  ,agrfct.SponsorName          
  ,ISNULL(agrfct.PILastName,'') + ', ' + ISNULL(agrfct.PIFirstName,'') AS 'PIName'          
 FROM          
  AgrAgreement agreement (nolock)        
  INNER JOIN        
 AgrAgreement_fct agrfct (nolock)      
      
 ON          
  agrfct.AgreementId = agreement.[ID]          
 INNER JOIN          
  AgrFundAwardType award (nolock)          
 ON          
  award.[ID] = agreement.AgrAgreementTypeId          
 INNER JOIN          
  AgrFundStatusType status (nolock)          
 ON          
  status.[ID] = agrfct.FundStatusTypeId          
 INNER JOIN          
     AgrFund_AgrAgreement_Map famap (nolock)          
 on       
     famap.AgrFundId = agrfct.FundId and           
     famap.AgrAgreementId = agrfct.AgreementId    
where 
agrfct.AgreementId =  @agreementId AND
agrfct.FundNumber <> @fundNumber  
      
          
-- >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>          
-- G E T  Terms and Conditions    R E S U L T S E T  F O R  U S E R            
-- Return a complete Terms and Conditions resultset from the agreementId          
-- >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>          
          
SELECT           
 ISNULL(terms.Terms, '') AS 'TermsAndConditions'          
FROM           
 AgrTermsAndConditions terms (nolock)          
WHERE           
 terms.AgrAgreementId = @agreementId          
-- >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>          
-- G E T  MileStones    R E S U L T S E T  F O R  U S E R            
-- Return a complete MileStones resultset from the agreementId          
-- >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>          
          
select distinct   
  ptDel.ReportName As 'Type'  
 ,cTab.Code_Desc As 'Description'  
 ,ptDel.CompletedDate as 'DateCompleted'  
 ,ptDel.DueDate As 'DateExpected' from InfoedPTDeliverable ptDel
inner join InfoedCodeTab cTab (nolock)
On cTab.Inst_Code = ptDel.Inst_Code
and cTab.CodeId = ptDel.ReportCat
INNER JOIN AgrAgreement agr (nolock)  
On agr.PropNumber = ptDel.Prop_no
where agr.Id = @agreementId
order by ptDel.CompletedDate Desc,ptDel.ReportName  

 if  @fundNumber is not null      
BEGIN      
 EXEC dbo.GetProjectHeader @fundNumber,NULL       
END  
SET NOCOUNT OFF          
END          


  



GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Creating [dbo].[spFdsDNCleanupAgreeSubContractor]'
GO

/***************************************************************************
* Name:			spFdsDNCleanupAgreeSubContractor
* Purpose:		Delete budget and AgrAgreement_SubContractor_Map
*				records for a subcontractor that was deleted in Rex
*
* PARAMETERS
* Name						Description					
* -------------				-----------------------------------------------------------
* @agrSubContractorMapId	Id of the agreement-to-subcontractor-map record to be deleted
* @agrBudgetContainerId		Id of the budget container to be deleted
*
* ERRORS USED				Description
* -------------				-----------------------------------------------------
* n/a
*
* RETURN VALUE
* Value    					Description					
* --------------			------------------------------------------------------
* @_exitStatus				An exit status of either true or false
***************************************************************************/
CREATE PROCEDURE dbo.spFdsDNCleanupAgreeSubContractor
(
	@agrSubContractorMapId	int,
	@agrBudgetContainerId	int
)
AS
BEGIN

	SET NOCOUNT ON

	DECLARE	@_errorValue	int

	BEGIN TRANSACTION spFdsDNCleanupAgreeSubContractor

	-- get AgrBudgetContainerViewId's
	SELECT		Id AS AgrBudgetContainerViewId
	INTO		#_tmpBudgetContainerViewIDs_to_Delete
	FROM		AgrBudgetContainerView
	WHERE		AgrBudgetContainerId = @agrBudgetContainerId

	-- now get all the related AgrBudgetId's
	SELECT		Id AS AgrBudgetId
	INTO		#_tmpBudgetIDs_to_Delete
	FROM		AgrBudget
	INNER JOIN	#_tmpBudgetContainerViewIDs_to_Delete
		ON			AgrBudget.AgrBudgetContainerViewId = #_tmpBudgetContainerViewIDs_to_Delete.AgrBudgetContainerViewId

	-- delete budget line items
	DELETE		AgrBudgetItem
	FROM		AgrBudgetItem
	INNER JOIN	#_tmpBudgetIDs_to_Delete
		ON			AgrBudgetItem.AgrBudgetId = #_tmpBudgetIDs_to_Delete.AgrBudgetId

	-- delete budget IC rates
	DELETE		AgrBudgetICRate
	FROM		AgrBudgetICRate
	INNER JOIN	#_tmpBudgetIDs_to_Delete
		ON			AgrBudgetICRate.AgrBudgetId = #_tmpBudgetIDs_to_Delete.AgrBudgetId

	-- delete the budgets
	DELETE		AgrBudget
	FROM		AgrBudget
	INNER JOIN	#_tmpBudgetIDs_to_Delete
		ON			AgrBudget.Id = #_tmpBudgetIDs_to_Delete.AgrBudgetId

	-- delete the budget container views
	DELETE		AgrBudgetContainerView
	FROM		AgrBudgetContainerView
	INNER JOIN	#_tmpBudgetContainerViewIDs_to_Delete
		ON			AgrBudgetContainerView.Id = #_tmpBudgetContainerViewIDs_to_Delete.AgrBudgetContainerViewId

	DROP TABLE	#_tmpBudgetIDs_to_Delete
	DROP TABLE	#_tmpBudgetContainerViewIDs_to_Delete

	-- delete budget container of this subcontractor
	DELETE		AgrBudgetContainer
	WHERE		Id = @agrBudgetContainerId

	-- delete subcontractor
	DELETE		AgrAgreement_SubContractor_Map
	WHERE		Id = @AgrSubcontractorMapId

	COMMIT TRANSACTION spFdsDNCleanupAgreeSubContractor

	SET NOCOUNT OFF

END

GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Creating [dbo].[PopulateAgreementFactLoader]'
GO
SET QUOTED_IDENTIFIER OFF
GO

Create Procedure PopulateAgreementFactLoader
AS

Begin

		truncate table AgrAgreement_fct

		if exists (select name from sysindexes where name = 'IX_AgrAgreement_Fct_Id' and id = object_id('dbo.AgrAgreement_Fct'))
		
		  DROP INDEX AgrAgreement_Fct.IX_AgrAgreement_Fct_Id
		
		

		if exists (select name from sysindexes where name = 'IX_AgrAgreement_Fct_ResourceId' and id = object_id('dbo.AgrAgreement_Fct'))
		DROP INDEX AgrAgreement_Fct.IX_AgrAgreement_Fct_ResourceId

	

		 

		if exists (select name from sysindexes where name = 'IX_AgrAgreement_Fct_AgreementId' and id = object_id('dbo.AgrAgreement_Fct'))
		DROP  INDEX [AgrAgreement_Fct].[IX_AgrAgreement_Fct_AgreementId] 

		
		 

		if exists (select name from sysindexes where name = 'IX_AgrAgreement_Fct_PrincipalInvestigatorId' and id = object_id('dbo.AgrAgreement_Fct'))
		 DROP  INDEX [AgrAgreement_Fct].[IX_AgrAgreement_Fct_PrincipalInvestigatorId]

	
		 

		if exists (select name from sysindexes where name = 'IX_AgrAgreement_Fct_FundId' and id = object_id('dbo.AgrAgreement_Fct'))
		 DROP  INDEX [AgrAgreement_Fct].[IX_AgrAgreement_Fct_FundId] 

		

		 

		if exists (select name from sysindexes where name = 'IX_AgrAgreement_Fct_FolderNumber' and id = object_id('dbo.AgrAgreement_Fct'))
		 DROP  INDEX [AgrAgreement_Fct].[IX_AgrAgreement_Fct_FolderNumber] 

	

		 

		if exists (select name from sysindexes where name = 'IX_AgrAgreement_Fct_FacilityId' and id = object_id('dbo.AgrAgreement_Fct'))
		 DROP  INDEX [AgrAgreement_Fct].[IX_AgrAgreement_Fct_FacilityId] 


		 

		if exists (select name from sysindexes where name = 'IX_AgrAgreement_Fct_WalkerNumber' and id = object_id('dbo.AgrAgreement_Fct'))
		 DROP  INDEX [AgrAgreement_Fct].[IX_AgrAgreement_Fct_WalkerNumber] 
		

		 

		if exists (select name from sysindexes where name = 'IX_AgrAgreement_Fct_BICSNumber' and id = object_id('dbo.AgrAgreement_Fct'))
		 DROP  INDEX [AgrAgreement_Fct].[IX_AgrAgreement_Fct_BICSNumber] 

		

		 

		if exists (select name from sysindexes where name = 'IX_AgrAgreement_Fct_SponsorId' and id = object_id('dbo.AgrAgreement_Fct'))
		 DROP  INDEX [AgrAgreement_Fct].[IX_AgrAgreement_Fct_SponsorId] 

	

		 

		if exists (select name from sysindexes where name = 'IX_AgrAgreement_Fct_BudgetStartDate' and id = object_id('dbo.AgrAgreement_Fct'))
		 DROP  INDEX [AgrAgreement_Fct].[IX_AgrAgreement_Fct_BudgetStartDate] 

		

		 

		if exists (select name from sysindexes where name = 'IX_AgrAgreement_Fct_BudgetEndDate' and id = object_id('dbo.AgrAgreement_Fct'))
		 DROP  INDEX [AgrAgreement_Fct].[IX_AgrAgreement_Fct_BudgetEndDate] 

		

		 

		if exists (select name from sysindexes where name = 'IX_AgrAgreement_Fct_OrganizationId' and id = object_id('dbo.AgrAgreement_Fct'))
		 DROP  INDEX [AgrAgreement_Fct].[IX_AgrAgreement_Fct_OrganizationId] 

		

		 

		if exists (select name from sysindexes where name = 'IX_AgrAgreement_Fct_ActivityTypeId' and id = object_id('dbo.AgrAgreement_Fct'))
		 DROP  INDEX [AgrAgreement_Fct].[IX_AgrAgreement_Fct_ActivityTypeId] 

		

		 

		if exists (select name from sysindexes where name = 'IX_AgrAgreement_Fct_PSActivityCode' and id = object_id('dbo.AgrAgreement_Fct'))
		 DROP  INDEX [AgrAgreement_Fct].[IX_AgrAgreement_Fct_PSActivityCode] 

		

		 

		if exists (select name from sysindexes where name = 'IX_AgrAgreement_Fct_SponsorTypeId' and id = object_id('dbo.AgrAgreement_Fct'))
		 DROP  INDEX [AgrAgreement_Fct].[IX_AgrAgreement_Fct_SponsorTypeId]

		

		 

		if exists (select name from sysindexes where name = 'IX_AgrAgreement_Fct_SponsorGroupTypeId' and id = object_id('dbo.AgrAgreement_Fct'))
		 DROP  INDEX [AgrAgreement_Fct].[IX_AgrAgreement_Fct_SponsorGroupTypeId]

		

		 

		if exists (select name from sysindexes where name = 'IX_AgrAgreement_Fct_FundStatusTypeId' and id = object_id('dbo.AgrAgreement_Fct'))
		 DROP  INDEX [AgrAgreement_Fct].[IX_AgrAgreement_Fct_FundStatusTypeId]

		

		 

		if exists (select name from sysindexes where name = 'IX_AgrAgreement_Fct_ProjectStartDate' and id = object_id('dbo.AgrAgreement_Fct'))
		 DROP  INDEX [AgrAgreement_Fct].[IX_AgrAgreement_Fct_ProjectStartDate]

		

		 

		if exists (select name from sysindexes where name = 'IX_AgrAgreement_Fct_ProjectEndDate' and id = object_id('dbo.AgrAgreement_Fct'))
		 DROP  INDEX [AgrAgreement_Fct].[IX_AgrAgreement_Fct_ProjectEndDate] 

		

		 

		if exists (select name from sysindexes where name = 'IX_AgrAgreement_Fct_StatusTypeId' and id = object_id('dbo.AgrAgreement_Fct'))
		 DROP  INDEX [AgrAgreement_Fct].[IX_AgrAgreement_Fct_StatusTypeId]

		

		declare @deleteStatusId int
		set @deleteStatusId = (select [Id] from AgrAgreementStatusType where [Name] = 'Delete')

		/*
		>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
		I N S E R T  A G R E E M E N T / F U N D  C O M B I N A T I O N S
		There can be only 1 instance of each fund and 1 to many instances of agreements because
		an agreement can have 0 to many funds.
		>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
		*/
		Insert Into AgrAgreement_fct (
			 ResourceId
			,OrganizationId
			,PrincipalInvestigatorId
			,AgreementId
			,FundId
			,ActivityTypeId
			,StatusTypeId
			,ICBaseTypeId
			,Title
			,ShortTitle
			,FolderNumber
			,DocumentNumber
			,FacilityId
			,ProjectCoreId
			,WalkerNumber
			,BICSNumber
			,IndirectCostRate
			,SponsorId
			,ProjectStartDate
			,ProjectEndDate
			,BudgetStartDate
			,BudgetEndDate
			,BudgetYear
			,DateCreated
			,SponsorName
			,SponsorNumber
			,FundNumber
			,PSActivityCode
			,PSActivityDescription
			,SponsorTypeId
			,SponsorGroupTypeId
			,PILastName
			,PIFirstName
			,PIMiddleName
			,FundStatusTypeId
			,AgrAgreementTypeId
			,SvcEntityId
			,Institution
			,Department
			,Unit
			,ChiefCode
			,AccountingCycleTypeId
			,AccountingCycle
			,ICBasis
			,CashBalance
			,AgrAgreementType
			,PropNumber
            ,OverallStatus
            ,ReceivedDate
            ,ParentFolderNumber
            ,LegacyIdentifier
            ,LegacySystemName
            ,FwkResourceId
			,IsCashBased
		)

		SELECT DISTINCT
			aa.FwkResourceId				AS ResourceId
			,edom.FwkDomainOrganizationId	AS OrganizationId
			,aa.PIPersonId					AS PrincipalInvestigatorId
			,aa.Id							AS AgreementId
			,f.AgrFundId					AS FundId
			,act.[Id] 						AS ActivityTypeId 	
			,aa.AgrAgreementStatusTypeId	AS StatusTypeId
			,1								AS ICBaseTypeId
			,CAST(aa.Title AS varchar(512))	AS Title
			,aa.ShortTitle					AS ShortTitle
			,aa.FolderNumber				AS FolderNumber
			,aa.DocumentNumber				AS DocumentNumber
			,(SELECT TOP 1 efm.AdmFacilityId FROM SvcEntity_AdmFacility_Map efm WHERE aa.SvcEntityId = efm.SvcEntityId 
				ORDER BY efm.PercentActivity, efm.AdmFacilityId DESC) AS FacilityId
			,(SELECT TOP 1 ah.IdentityTag FROM AgrAgreementHierarchy ah WHERE aa.FolderNumber = ah.FolderNumber 
				ORDER BY ah.Sequence DESC)	AS ProjectCoreId
			,case cc.AgrCostCenterSystemTypeId 
				when 1 then cc.Number --MGH
			 end							AS WalkerNumber
			,case cc.AgrCostCenterSystemTypeId 
				when 2 then cc.Number --Brigham
			 end							AS BICSNumber
			,0 IndirectCostRate
			,esm.AdmSponsorId				AS SponsorId
			,aa.ProjectStartDate			AS ProjectStartDate
			,aa.ProjectEndDate				AS ProjectEndDate
			,null							AS BudgetStartDate
			,null							AS BudgetEndDate
			,0								AS BudgetYear
			,GetDate()						AS DateCreated
			,spr.[Name]						AS SponsorName
			,esm.SponsorNumber				AS SponsorNumber
			,f.FundNumber					AS FundNumber
			,acty.PSCode					AS PSActivityCode
			,acty.[Description]				AS PSActivityDescription
			,spr.AdmSponsorTypeId			AS SponsorTypeId
			,stgtm.[AdmSponsorGroupTypeId]	AS SponsorGroupTypeId
			,p.LastName						AS PILastName
			,p.FirstName					AS PIFirstName
			,p.MiddleName					AS PIMiddleName
			,f.AgrFundStatusTypeId			AS FundStatusTypeId
			,aa.AgrAgreementTypeId			AS AgrAgreementTypeId
			,aa.SvcEntityId					AS SvcEntityId
			,o4.Institution 				as Institution
			,Department.[Name]				as department
			,Unit.[Name]					as unit
			,o4.ChiefCode
			,f.FinAccountCycleTypeId
			,isnull(fcyc.[Name],'')			as AccountingCycle
			,'MTDC'
			,0
			,(Select agt.[name] from agragreementtype agt 
			  where agt.id = aa.AgrAgreementTypeId) as AgrAgreementType
			 ,aa.PropNumber
           ,aa.OverallStatus
           ,aa.ReceivedDate
           ,aa.ParentFolderNumber
           ,aa.LegacyIdentifier
           ,aa.LegacySystemName
           ,aa.FwkResourceId
		   ,IsNull(agt.[IsCashBased],0)	as IsCashBased

		FROM AgrAgreement aa
		LEFT OUTER JOIN agragreementtype agt				ON agt.id = aa.AgrAgreementTypeId
		LEFT OUTER JOIN	SvcEntity_FwkDomainOrganization_Map edom
															ON aa.SvcEntityId = edom.SvcEntityId 
		LEFT OUTER JOIN AgrFund_AgrAgreement_Map f			ON aa.Id = f.AgrAgreementId 
		LEFT OUTER JOIN	AgrCostCenter_AgrFund_Map ccfm		ON f.Id = ccfm.AgrFundAgreementMapId 
		LEFT OUTER JOIN	AgrCostCenter cc					ON ccfm.AgrCostCenterId = cc.Id
		LEFT OUTER JOIN	SvcEntity_AdmSponsor_Map esm		ON aa.SvcEntityId = esm.SvcEntityId
		LEFT OUTER JOIN AdmSponsor spr 						ON spr.Id = esm.AdmSponsorId
		LEFT OUTER JOIN AdmSponsorType_GroupType_Map stgtm	ON stgtm.AdmSponsorTypeId = spr.AdmSponsorTypeId
		LEFT OUTER JOIN AdmPerson p							ON p.[Id] = aa.PIPersonId
		LEFT OUTER JOIN AgrActivity act						ON act.AgrAgreementId = aa.[Id] 
																and act.sequenceno = (select min(act1.sequenceno) from AgrActivity act1
																					   where act1.AgrAgreementId = aa.[Id] and act1.sequenceno is not null)
		LEFT OUTER JOIN AgrActivityType acty				ON acty.Id = act.AgrActivityTypeId
		left outer join	fwkdomainorganization o4  			ON o4.id = edom.FwkDomainOrganizationId
		left outer join fwkdomainorganization Department	ON Department.Id = o4.DepartmentId
		left outer join fwkdomainorganization Unit			ON Unit.Id = o4.UnitId
		left outer join FinAccountCycleType fcyc			ON fcyc.id = f.FinAccountCycleTypeId
		where 
			aa.IsCurrent = 1 
			and aa.IsAmendment = 0
			AND edom.FwkOrganizationRelationshipTypeId = 1 -- Primary organization
			and esm.AdmSponsorRelationTypeId =1 --Primary Sponsor
			and aa.DocumentNumber = (Select max(aa1.DocumentNumber) 
									 from AgrAgreement aa1 
									 where 
										aa1.foldernumber = aa.foldernumber
										and aa1.IsCurrent = 1
										and aa1.IsAmendment = 0
										and aa1.DocumentNumber is not null )
			and aa.AgrAgreementStatusTypeId <> @deleteStatusId

		 


		 CREATE  INDEX [IX_AgrAgreement_Fct_AgreementId] ON [dbo].[AgrAgreement_Fct]([AgreementId]) ON [PRIMARY]

		

		CREATE UNIQUE INDEX [IX_AgrAgreement_Fct_Id] ON [dbo].[AgrAgreement_Fct]([Id]) ON [PRIMARY]
		
		/*
		>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
		U P D A T E  A W A R D E D  A G R E E M E N T S  N O  A D J U S T M E N T  --  C U R R E N T / P A S T  B U D G E T 
		>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
		*/
		Update
			agf
		Set
			IndirectCostRate = isnull((select top 1 CAST(isnull(bicr.Rate,0) AS float) from AgrBudget br 
					inner join AgrBudgetICRate bicr	ON br.Id = bicr.AgrBudgetId 
					where bcv.Id = br.AgrBudgetContainerViewId 
						and br.AgrBudgetTypeId = 1  and br.AgrFundAgreeMapId = f.Id
						and br.startdate = (select max(br1.startdate) from AgrBudget br1 
											where br1.AgrBudgetContainerViewId = bcv.Id  
												and br1.AgrFundAgreeMapId = br.AgrFundAgreeMapId 
												and br1.startdate is not null
												and br1.startdate <= getdate())
						AND bicr.SequenceNo = 1)
				,0)
			,BudgetStartDate = BudgetStart.StartDate
			,BudgetEndDate = BudgetEnd.EndDate
			,BudgetYear = IsNull((select top 1 byr.year from AgrBudget byr
					 where bcv.Id = byr.AgrBudgetContainerViewId 
						and byr.AgrBudgetTypeId = 1  
						and byr.AgrFundAgreeMapId = f.Id
						and byr.startdate = (select max(byr1.startdate) 
		 									from AgrBudget byr1 
											where 
												byr1.AgrBudgetContainerViewId = bcv.Id 
												and byr1.AgrFundAgreeMapId = byr.AgrFundAgreeMapId 
												and byr1.startdate is not null
												and byr1.startdate <= getdate() )
					),0)
			,ICBasis = IsNull(ICBase.[Code],'MTDC')
			,ICBaseTypeId = IsNull(ICBase.[Id],1)
		FROM AgrAgreement_fct agf
		INNER JOIN AgrAgreement aa							ON aa.[Id] = agf.agreementid
		LEFT OUTER JOIN AgrFund_AgrAgreement_Map f			ON agf.[fundId] = f.AgrfundId 
		LEFT OUTER JOIN AgrBudgetContainer bc				ON aa.AgrBudgetContainerId = bc.Id
		LEFT OUTER JOIN finicbasetype icbase				ON icbase.id = bc.indirectcostbaseid
		LEFT OUTER JOIN AgrBudgetContainerView bcv			ON bc.Id = bcv.AgrBudgetContainerId
		LEFT OUTER JOIN agrbudget agb 						ON agb.AgrBudgetContainerViewId = bcv.Id and agb.AgrFundAgreeMapId = f.Id
		LEFT OUTER JOIN (select  bs.AgrBudgetContainerViewId ,bs.AgrBudgetTypeId ,bs.AgrFundAgreeMapId ,min(bs.startdate) AS StartDate 
						 from AgrBudget bs where bs.IsAdjustment = 0 and bs.startdate is not null
						 group by bs.AgrBudgetContainerViewId, bs.AgrBudgetTypeId ,bs.AgrFundAgreeMapId) BudgetStart	
															ON BudgetStart.AgrBudgetContainerViewId = bcv.Id 
																and BudgetStart.AgrFundAgreeMapId = f.Id
		LEFT OUTER JOIN (select  bs.AgrBudgetContainerViewId,bs.AgrBudgetTypeId, bs.AgrFundAgreeMapId, max(bs.enddate) AS EndDate 
						 from AgrBudget bs where bs.IsAdjustment = 0 and bs.enddate is not null
						 group by bs.AgrBudgetContainerViewId, bs.AgrBudgetTypeId ,bs.AgrFundAgreeMapId) BudgetEnd
															ON BudgetEnd.AgrBudgetContainerViewId = bcv.Id 
																and BudgetEnd.AgrFundAgreeMapId = f.Id
		where 
			bcv.AgrBudgetViewTypeId = 3 -- Fully Executed/Awarded view of budget
			AND agb.IsAdjustment = 0 -- Must not be an adjustment budget
			and BudgetStart.AgrBudgetTypeId = 1 -- annual budget
			and BudgetEnd.AgrBudgetTypeId = 1 -- annual budget
			and bc.agrBudgetTemplateTypeId = 1 -- Agreement Budget template type
		/*
		>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
		U P D A T E  A W A R D E D  A G R E E M E N T S  N O  A D J U S T M E N T --  F U T U R E  B U D G E T 
		>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
		*/
		Update
			agf
		Set
			IndirectCostRate = isnull((select top 1 CAST(isnull(bicr.Rate,0) AS float) from AgrBudget br 
					inner join AgrBudgetICRate bicr	ON br.Id = bicr.AgrBudgetId 
					where bcv.Id = br.AgrBudgetContainerViewId 
						and br.AgrBudgetTypeId = 1  and br.AgrFundAgreeMapId = f.Id
						and br.startdate = (select min(br1.startdate) from AgrBudget br1 
											where br1.AgrBudgetContainerViewId = bcv.Id  
												and br1.AgrFundAgreeMapId = br.AgrFundAgreeMapId 
												and br1.startdate is not null
												and br1.startdate > getdate())
						AND bicr.SequenceNo = 1)
				,0)
			,BudgetStartDate = BudgetStart.StartDate
			,BudgetEndDate = BudgetEnd.EndDate
			,BudgetYear = IsNull((select top 1 byr.year from AgrBudget byr
					 where bcv.Id = byr.AgrBudgetContainerViewId 
						and byr.AgrBudgetTypeId = 1  
						and byr.AgrFundAgreeMapId = f.Id
						and byr.startdate = (select min(byr1.startdate) 
		 									from AgrBudget byr1 
											where 
												byr1.AgrBudgetContainerViewId = bcv.Id 
												and byr1.AgrFundAgreeMapId = byr.AgrFundAgreeMapId 
												and byr1.startdate is not null
												and byr1.startdate > getdate() )
					),0)
			,ICBasis = IsNull(ICBase.[Code],'MTDC')
			,ICBaseTypeId = IsNull(ICBase.[Id],1)
		FROM AgrAgreement_fct agf
		INNER JOIN AgrAgreement aa							ON aa.[Id] = agf.agreementid
		LEFT OUTER JOIN AgrFund_AgrAgreement_Map f			ON agf.[fundId] = f.AgrfundId 
		LEFT OUTER JOIN AgrBudgetContainer bc				ON aa.AgrBudgetContainerId = bc.Id
		LEFT OUTER JOIN finicbasetype icbase				ON icbase.id = bc.indirectcostbaseid
		LEFT OUTER JOIN AgrBudgetContainerView bcv			ON bc.Id = bcv.AgrBudgetContainerId
		LEFT OUTER JOIN agrbudget agb 						ON agb.AgrBudgetContainerViewId = bcv.Id and agb.AgrFundAgreeMapId = f.Id
		LEFT OUTER JOIN (select  bs.AgrBudgetContainerViewId ,bs.AgrBudgetTypeId ,bs.AgrFundAgreeMapId ,min(bs.startdate) AS StartDate 
						 from AgrBudget bs where bs.IsAdjustment = 0 and bs.startdate is not null
						 group by bs.AgrBudgetContainerViewId, bs.AgrBudgetTypeId ,bs.AgrFundAgreeMapId) BudgetStart	
															ON BudgetStart.AgrBudgetContainerViewId = bcv.Id 
																and BudgetStart.AgrFundAgreeMapId = f.Id
		LEFT OUTER JOIN (select  bs.AgrBudgetContainerViewId,bs.AgrBudgetTypeId, bs.AgrFundAgreeMapId, max(bs.enddate) AS EndDate 
						 from AgrBudget bs where bs.IsAdjustment = 0 and bs.enddate is not null
						 group by bs.AgrBudgetContainerViewId, bs.AgrBudgetTypeId ,bs.AgrFundAgreeMapId) BudgetEnd
															ON BudgetEnd.AgrBudgetContainerViewId = bcv.Id 
																and BudgetEnd.AgrFundAgreeMapId = f.Id
		where 
			bcv.AgrBudgetViewTypeId = 3 -- Fully Executed/Awarded view of budget
			AND agb.IsAdjustment = 0 -- Must not be an adjustment budget
			and BudgetStart.AgrBudgetTypeId = 1 -- annual budget
			and BudgetEnd.AgrBudgetTypeId = 1 -- annual budget
			and bc.agrBudgetTemplateTypeId = 1 -- Agreement Budget template type
			and agf.BudgetYear = 0
		/*
		>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
		U P D A T E  A W A R D E D  A G R E E M E N T S  A D J U S T M E N T  --  C U R R E N T / P A S T  B U D G E T 
		>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
		*/
		Update
			agf
		Set
			IndirectCostRate = isnull((select top 1 CAST(isnull(bicr.Rate,0) AS float) from AgrBudget br 
					inner join AgrBudgetICRate bicr	ON br.Id = bicr.AgrBudgetId 
					where bcv.Id = br.AgrBudgetContainerViewId 
						and br.AgrBudgetTypeId = 1  and br.AgrFundAgreeMapId = f.Id
						and br.startdate = (select max(br1.startdate) from AgrBudget br1 
											where br1.AgrBudgetContainerViewId = bcv.Id  
												and br1.AgrFundAgreeMapId = br.AgrFundAgreeMapId 
												and br1.startdate is not null
												and br1.startdate <= getdate())
						AND bicr.SequenceNo = 1)
				,0)
			,BudgetStartDate = BudgetStart.StartDate
			,BudgetEndDate = BudgetEnd.EndDate
			,BudgetYear = IsNull((select top 1 byr.year from AgrBudget byr
					 where bcv.Id = byr.AgrBudgetContainerViewId 
						and byr.AgrBudgetTypeId = 1  
						and byr.AgrFundAgreeMapId = f.Id
						and byr.startdate = (select max(byr1.startdate) 
		 									from AgrBudget byr1 
											where 
												byr1.AgrBudgetContainerViewId = bcv.Id 
												and byr1.AgrFundAgreeMapId = byr.AgrFundAgreeMapId 
												and byr1.startdate is not null
												and byr1.startdate <= getdate() )
					),0)
			,ICBasis = IsNull(ICBase.[Code],'MTDC')
			,ICBaseTypeId = IsNull(ICBase.[Id],1)
		FROM AgrAgreement_fct agf
		INNER JOIN AgrAgreement aa							ON aa.[Id] = agf.agreementid
		LEFT OUTER JOIN AgrFund_AgrAgreement_Map f			ON agf.[fundId] = f.AgrfundId 
		LEFT OUTER JOIN AgrBudgetContainer bc				ON aa.AgrBudgetContainerId = bc.Id
		LEFT OUTER JOIN finicbasetype icbase				ON icbase.id = bc.indirectcostbaseid
		LEFT OUTER JOIN AgrBudgetContainerView bcv			ON bc.Id = bcv.AgrBudgetContainerId
		LEFT OUTER JOIN agrbudget agb 						ON agb.AgrBudgetContainerViewId = bcv.Id and agb.AgrFundAgreeMapId = f.Id
		LEFT OUTER JOIN (select  bs.AgrBudgetContainerViewId ,bs.AgrBudgetTypeId ,bs.AgrFundAgreeMapId ,min(bs.startdate) AS StartDate 
						 from AgrBudget bs where bs.IsAdjustment = 1 and bs.startdate is not null
						 group by bs.AgrBudgetContainerViewId, bs.AgrBudgetTypeId ,bs.AgrFundAgreeMapId) BudgetStart	
															ON BudgetStart.AgrBudgetContainerViewId = bcv.Id 
																and BudgetStart.AgrFundAgreeMapId = f.Id
		LEFT OUTER JOIN (select  bs.AgrBudgetContainerViewId,bs.AgrBudgetTypeId, bs.AgrFundAgreeMapId, max(bs.enddate) AS EndDate 
						 from AgrBudget bs where bs.IsAdjustment = 1 and bs.enddate is not null
						 group by bs.AgrBudgetContainerViewId, bs.AgrBudgetTypeId ,bs.AgrFundAgreeMapId) BudgetEnd
															ON BudgetEnd.AgrBudgetContainerViewId = bcv.Id 
																and BudgetEnd.AgrFundAgreeMapId = f.Id
		where 
			bcv.AgrBudgetViewTypeId = 3 -- Fully Executed/Awarded view of budget
			AND agb.IsAdjustment = 1 -- Must be an adjustment budget
			and BudgetStart.AgrBudgetTypeId = 1 -- annual budget
			and BudgetEnd.AgrBudgetTypeId = 1 -- annual budget
			and bc.agrBudgetTemplateTypeId = 1 -- Agreement Budget template type
			and agf.BudgetYear = 0

		/*
		>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
		U P D A T E  A W A R D E D  A G R E E M E N T S  A D J U S T M E N T --  F U T U R E  B U D G E T 
		>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
		*/
		Update
			agf
		Set
			IndirectCostRate = isnull((select top 1 CAST(isnull(bicr.Rate,0) AS float) from AgrBudget br 
					inner join AgrBudgetICRate bicr	ON br.Id = bicr.AgrBudgetId 
					where bcv.Id = br.AgrBudgetContainerViewId 
						and br.AgrBudgetTypeId = 1  and br.AgrFundAgreeMapId = f.Id
						and br.startdate = (select min(br1.startdate) from AgrBudget br1 
											where br1.AgrBudgetContainerViewId = bcv.Id  
												and br1.AgrFundAgreeMapId = br.AgrFundAgreeMapId 
												and br1.startdate is not null
												and br1.startdate > getdate())
						AND bicr.SequenceNo = 1)
				,0)
			,BudgetStartDate = BudgetStart.StartDate
			,BudgetEndDate = BudgetEnd.EndDate
			,BudgetYear = IsNull((select top 1 byr.year from AgrBudget byr
					 where bcv.Id = byr.AgrBudgetContainerViewId 
						and byr.AgrBudgetTypeId = 1  
						and byr.AgrFundAgreeMapId = f.Id
						and byr.startdate = (select min(byr1.startdate) 
		 									from AgrBudget byr1 
											where 
												byr1.AgrBudgetContainerViewId = bcv.Id 
												and byr1.AgrFundAgreeMapId = byr.AgrFundAgreeMapId 
												and byr1.startdate is not null
												and byr1.startdate > getdate() )
					),0)
			,ICBasis = IsNull(ICBase.[Code],'MTDC')
			,ICBaseTypeId = IsNull(ICBase.[Id],1)
		FROM AgrAgreement_fct agf
		INNER JOIN AgrAgreement aa							ON aa.[Id] = agf.agreementid
		LEFT OUTER JOIN AgrFund_AgrAgreement_Map f			ON agf.[fundId] = f.AgrfundId 
		LEFT OUTER JOIN AgrBudgetContainer bc				ON aa.AgrBudgetContainerId = bc.Id
		LEFT OUTER JOIN finicbasetype icbase				ON icbase.id = bc.indirectcostbaseid
		LEFT OUTER JOIN AgrBudgetContainerView bcv			ON bc.Id = bcv.AgrBudgetContainerId
		LEFT OUTER JOIN agrbudget agb 						ON agb.AgrBudgetContainerViewId = bcv.Id and agb.AgrFundAgreeMapId = f.Id
		LEFT OUTER JOIN (select  bs.AgrBudgetContainerViewId ,bs.AgrBudgetTypeId ,bs.AgrFundAgreeMapId ,min(bs.startdate) AS StartDate 
						 from AgrBudget bs where bs.IsAdjustment = 1 and bs.startdate is not null
						 group by bs.AgrBudgetContainerViewId, bs.AgrBudgetTypeId ,bs.AgrFundAgreeMapId) BudgetStart	
															ON BudgetStart.AgrBudgetContainerViewId = bcv.Id 
																and BudgetStart.AgrFundAgreeMapId = f.Id
		LEFT OUTER JOIN (select  bs.AgrBudgetContainerViewId,bs.AgrBudgetTypeId, bs.AgrFundAgreeMapId, max(bs.enddate) AS EndDate 
						 from AgrBudget bs where bs.IsAdjustment = 1 and bs.enddate is not null
						 group by bs.AgrBudgetContainerViewId, bs.AgrBudgetTypeId ,bs.AgrFundAgreeMapId) BudgetEnd
															ON BudgetEnd.AgrBudgetContainerViewId = bcv.Id 
																and BudgetEnd.AgrFundAgreeMapId = f.Id
		where 
			bcv.AgrBudgetViewTypeId = 3 -- Fully Executed/Awarded view of budget
			AND agb.IsAdjustment = 1 -- Must be an adjustment budget
			and BudgetStart.AgrBudgetTypeId = 1 -- annual budget
			and BudgetEnd.AgrBudgetTypeId = 1 -- annual budget
			and bc.agrBudgetTemplateTypeId = 1 -- Agreement Budget template type
			and agf.BudgetYear = 0


		/*
		>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
		U P D A T E  P E N D I N G  A G R E E M E N T S  N O  A D J U S T M E N T  --  C U R R E N T / P A S T  B U D G E T
		>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
		*/
		Update
			agf
		Set
			IndirectCostRate = isnull((select top 1 CAST(isnull(bicr.Rate,0) AS float) from AgrBudget br 
					inner join AgrBudgetICRate bicr	ON br.Id = bicr.AgrBudgetId 
					where bcv.Id = br.AgrBudgetContainerViewId 
						and br.AgrBudgetTypeId = 1  and IsNull(br.AgrFundAgreeMapId,0) = IsNull(f.Id,0)
						and br.startdate = (select max(br1.startdate) from AgrBudget br1 
											where br1.AgrBudgetContainerViewId = bcv.Id 
												and IsNull(br1.AgrFundAgreeMapId,0) = IsNull(br.AgrFundAgreeMapId,0) 
											and br1.StartDate is not null
											and br1.startdate <= getdate())
						AND bicr.SequenceNo = 1)
				,0)
			,BudgetStartDate = BudgetStart.StartDate
			,BudgetEndDate = BudgetEnd.EndDate
			,BudgetYear = IsNull((select top 1 byr.year from AgrBudget byr
					 where bcv.Id = byr.AgrBudgetContainerViewId 
						and byr.AgrBudgetTypeId = 1  
						and IsNull(byr.AgrFundAgreeMapId,0) = IsNull(f.Id,0)
						and byr.startdate = (select max(byr1.startdate) 
		 									from AgrBudget byr1 
											where byr1.AgrBudgetContainerViewId = bcv.Id 
												and IsNull(byr1.AgrFundAgreeMapId,0) = IsNull(byr.AgrFundAgreeMapId,0) 
												and byr1.StartDate is not null
												and byr1.startdate <= getdate())
					),0)
			,ICBasis = IsNull(ICBase.[Code],'MTDC')
			,ICBaseTypeId = IsNull(ICBase.[Id],1)
		FROM AgrAgreement_fct agf
		INNER JOIN AgrAgreement aa							ON aa.[Id] = agf.agreementid
		LEFT OUTER JOIN AgrFund_AgrAgreement_Map f			ON agf.[fundId] = f.AgrfundId  
		LEFT OUTER JOIN AgrBudgetContainer bc				ON aa.AgrBudgetContainerId = bc.Id
		LEFT OUTER JOIN finicbasetype icbase				ON icbase.id = bc.indirectcostbaseid
		LEFT OUTER JOIN AgrBudgetContainerView bcv			ON bc.Id = bcv.AgrBudgetContainerId 
		LEFT OUTER JOIN agrbudget agb 						ON agb.AgrBudgetContainerViewId = bcv.Id and IsNull(agb.AgrFundAgreeMapId,0) = IsNull(f.Id,0)
		LEFT OUTER JOIN (select  bs.AgrBudgetContainerViewId ,bs.AgrBudgetTypeId ,bs.AgrFundAgreeMapId ,min(bs.startdate) AS StartDate 
						 from AgrBudget bs where bs.IsAdjustment = 0 and bs.startdate is not null
						 group by bs.AgrBudgetContainerViewId, bs.AgrBudgetTypeId ,bs.AgrFundAgreeMapId) BudgetStart	
															ON BudgetStart.AgrBudgetContainerViewId = bcv.Id 
																and IsNull(BudgetStart.AgrFundAgreeMapId,0) = IsNull(f.Id,0)
		LEFT OUTER JOIN (select  bs.AgrBudgetContainerViewId,bs.AgrBudgetTypeId, bs.AgrFundAgreeMapId, max(bs.enddate) AS EndDate 
						 from AgrBudget bs where bs.IsAdjustment = 0  and bs.enddate is not null
						 group by bs.AgrBudgetContainerViewId, bs.AgrBudgetTypeId ,bs.AgrFundAgreeMapId) BudgetEnd
															ON BudgetEnd.AgrBudgetContainerViewId = bcv.Id 
																and IsNull(BudgetEnd.AgrFundAgreeMapId,0) = IsNull(f.Id,0)
		where 
			bcv.AgrBudgetViewTypeId = 1 -- Pending view of budget
			AND agb.IsAdjustment = 0 -- Must not be an adjustment budget
			and BudgetStart.AgrBudgetTypeId = 1 -- annual budget
			and BudgetEnd.AgrBudgetTypeId = 1 -- annual budget
			and bc.agrBudgetTemplateTypeId = 1 -- Agreement Budget template type
			and agf.BudgetYear = 0

		/*
		>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
		U P D A T E  P E N D I N G  A G R E E M E N T S  N O  A D J U S T M E N T  --  F U T U R E  B U D G E T
		>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
		*/
		Update
			agf
		Set
			IndirectCostRate = isnull((select top 1 CAST(isnull(bicr.Rate,0) AS float) from AgrBudget br 
					inner join AgrBudgetICRate bicr	ON br.Id = bicr.AgrBudgetId 
					where bcv.Id = br.AgrBudgetContainerViewId 
						and br.AgrBudgetTypeId = 1  and IsNull(br.AgrFundAgreeMapId,0) = IsNull(f.Id,0)
						and br.startdate = (select min(br1.startdate) from AgrBudget br1 
											where br1.AgrBudgetContainerViewId = bcv.Id 
												and IsNull(br1.AgrFundAgreeMapId,0) = IsNull(br.AgrFundAgreeMapId ,0)
											and br1.StartDate is not null
											and br1.startdate > getdate())
						AND bicr.SequenceNo = 1)
				,0)
			,BudgetStartDate = BudgetStart.StartDate
			,BudgetEndDate = BudgetEnd.EndDate
			,BudgetYear = IsNull((select top 1 byr.year from AgrBudget byr
					 where bcv.Id = byr.AgrBudgetContainerViewId 
						and byr.AgrBudgetTypeId = 1  
						and IsNull(byr.AgrFundAgreeMapId,0) = IsNull(f.Id,0)
						and byr.startdate = (select min(byr1.startdate) 
		 									from AgrBudget byr1 
											where byr1.AgrBudgetContainerViewId = bcv.Id 
												and IsNull(byr1.AgrFundAgreeMapId,0) = IsNull(byr.AgrFundAgreeMapId ,0)
												and byr1.StartDate is not null
												and byr1.startdate > getdate())
					),0)
			,ICBasis = IsNull(ICBase.[Code],'MTDC')
			,ICBaseTypeId = IsNull(ICBase.[Id],1)
		FROM AgrAgreement_fct agf
		INNER JOIN AgrAgreement aa							ON aa.[Id] = agf.agreementid
		LEFT OUTER JOIN AgrFund_AgrAgreement_Map f			ON agf.[fundId] = f.AgrfundId  
		LEFT OUTER JOIN AgrBudgetContainer bc				ON aa.AgrBudgetContainerId = bc.Id
		LEFT OUTER JOIN finicbasetype icbase				ON icbase.id = bc.indirectcostbaseid
		LEFT OUTER JOIN AgrBudgetContainerView bcv			ON bc.Id = bcv.AgrBudgetContainerId 
		LEFT OUTER JOIN agrbudget agb 						ON agb.AgrBudgetContainerViewId = bcv.Id and IsNull(agb.AgrFundAgreeMapId,0) = IsNull(f.Id,0)
		LEFT OUTER JOIN (select  bs.AgrBudgetContainerViewId ,bs.AgrBudgetTypeId ,bs.AgrFundAgreeMapId ,min(bs.startdate) AS StartDate 
						 from AgrBudget bs where bs.IsAdjustment = 0 and bs.startdate is not null
						 group by bs.AgrBudgetContainerViewId, bs.AgrBudgetTypeId ,bs.AgrFundAgreeMapId) BudgetStart	
															ON BudgetStart.AgrBudgetContainerViewId = bcv.Id 
																and IsNull(BudgetStart.AgrFundAgreeMapId,0) = IsNull(f.Id,0)
		LEFT OUTER JOIN (select  bs.AgrBudgetContainerViewId,bs.AgrBudgetTypeId, bs.AgrFundAgreeMapId, max(bs.enddate) AS EndDate 
						 from AgrBudget bs where bs.IsAdjustment = 0  and bs.enddate is not null
						 group by bs.AgrBudgetContainerViewId, bs.AgrBudgetTypeId ,bs.AgrFundAgreeMapId) BudgetEnd
															ON BudgetEnd.AgrBudgetContainerViewId = bcv.Id 
																and IsNull(BudgetEnd.AgrFundAgreeMapId,0) = IsNull(f.Id,0)
		where 
			bcv.AgrBudgetViewTypeId = 1 -- Pending view of budget
			AND agb.IsAdjustment = 0 -- Must not be an adjustment budget
			and BudgetStart.AgrBudgetTypeId = 1 -- annual budget
			and BudgetEnd.AgrBudgetTypeId = 1 -- annual budget
			and bc.agrBudgetTemplateTypeId = 1 -- Agreement Budget template type
			and agf.BudgetYear = 0

		/*
		>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
		U P D A T E  P E N D I N G  A G R E E M E N T S  A D J U S T M E N T  --  C U R R E N T / P A S T  B U D G E T
		>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
		*/
		Update
			agf
		Set
			IndirectCostRate = isnull((select top 1 CAST(isnull(bicr.Rate,0) AS float) from AgrBudget br 
					inner join AgrBudgetICRate bicr	ON br.Id = bicr.AgrBudgetId 
					where bcv.Id = br.AgrBudgetContainerViewId 
						and br.AgrBudgetTypeId = 1  and IsNull(br.AgrFundAgreeMapId,0) = IsNull(f.Id,0)
						and br.startdate = (select max(br1.startdate) from AgrBudget br1 
											where br1.AgrBudgetContainerViewId = bcv.Id 
												and IsNull(br1.AgrFundAgreeMapId,0) = IsNull(br.AgrFundAgreeMapId,0) 
											and br1.StartDate is not null
											and br1.startdate <= getdate())
						AND bicr.SequenceNo = 1)
				,0)
			,BudgetStartDate = BudgetStart.StartDate
			,BudgetEndDate = BudgetEnd.EndDate
			,BudgetYear = IsNull((select top 1 byr.year from AgrBudget byr
					 where bcv.Id = byr.AgrBudgetContainerViewId 
						and byr.AgrBudgetTypeId = 1  
						and IsNull(byr.AgrFundAgreeMapId,0) = IsNull(f.Id,0)
						and byr.startdate = (select max(byr1.startdate) 
		 									from AgrBudget byr1 
											where byr1.AgrBudgetContainerViewId = bcv.Id 
												and IsNull(byr1.AgrFundAgreeMapId,0) = IsNull(byr.AgrFundAgreeMapId,0) 
												and byr1.StartDate is not null
												and byr1.startdate <= getdate())
					),0)
			,ICBasis = IsNull(ICBase.[Code],'MTDC')
			,ICBaseTypeId = IsNull(ICBase.[Id],1)
		FROM AgrAgreement_fct agf
		INNER JOIN AgrAgreement aa							ON aa.[Id] = agf.agreementid
		LEFT OUTER JOIN AgrFund_AgrAgreement_Map f			ON agf.[fundId] = f.AgrfundId  
		LEFT OUTER JOIN AgrBudgetContainer bc				ON aa.AgrBudgetContainerId = bc.Id
		LEFT OUTER JOIN finicbasetype icbase				ON icbase.id = bc.indirectcostbaseid
		LEFT OUTER JOIN AgrBudgetContainerView bcv			ON bc.Id = bcv.AgrBudgetContainerId 
		LEFT OUTER JOIN agrbudget agb 						ON agb.AgrBudgetContainerViewId = bcv.Id and IsNull(agb.AgrFundAgreeMapId,0) = IsNull(f.Id,0)
		LEFT OUTER JOIN (select  bs.AgrBudgetContainerViewId ,bs.AgrBudgetTypeId ,bs.AgrFundAgreeMapId ,min(bs.startdate) AS StartDate 
						 from AgrBudget bs where bs.IsAdjustment = 1 and bs.startdate is not null
						 group by bs.AgrBudgetContainerViewId, bs.AgrBudgetTypeId ,bs.AgrFundAgreeMapId) BudgetStart	
															ON BudgetStart.AgrBudgetContainerViewId = bcv.Id 
																and IsNull(BudgetStart.AgrFundAgreeMapId,0) = IsNull(f.Id,0)
		LEFT OUTER JOIN (select  bs.AgrBudgetContainerViewId,bs.AgrBudgetTypeId, bs.AgrFundAgreeMapId, max(bs.enddate) AS EndDate 
						 from AgrBudget bs where bs.IsAdjustment = 1  and bs.enddate is not null
						 group by bs.AgrBudgetContainerViewId, bs.AgrBudgetTypeId ,bs.AgrFundAgreeMapId) BudgetEnd
															ON BudgetEnd.AgrBudgetContainerViewId = bcv.Id 
																and IsNull(BudgetEnd.AgrFundAgreeMapId,0) = IsNull(f.Id,0)
		where 
			bcv.AgrBudgetViewTypeId = 1 -- Pending view of budget
			AND agb.IsAdjustment = 1 -- Must not be an adjustment budget
			and BudgetStart.AgrBudgetTypeId = 1 -- annual budget
			and BudgetEnd.AgrBudgetTypeId = 1 -- annual budget
			and bc.agrBudgetTemplateTypeId = 1 -- Agreement Budget template type
			and agf.BudgetYear = 0

		/*
		>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
		U P D A T E  P E N D I N G  A G R E E M E N T S  A D J U S T M E N T  --  F U T U R E  B U D G E T
		>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
		*/
		Update
			agf
		Set
			IndirectCostRate = isnull((select top 1 CAST(isnull(bicr.Rate,0) AS float) from AgrBudget br 
					inner join AgrBudgetICRate bicr	ON br.Id = bicr.AgrBudgetId 
					where bcv.Id = br.AgrBudgetContainerViewId 
						and br.AgrBudgetTypeId = 1  and IsNull(br.AgrFundAgreeMapId,0) = IsNull(f.Id,0)
						and br.startdate = (select min(br1.startdate) from AgrBudget br1 
											where br1.AgrBudgetContainerViewId = bcv.Id 
												and IsNull(br1.AgrFundAgreeMapId,0) = IsNull(br.AgrFundAgreeMapId ,0)
											and br1.StartDate is not null
											and br1.startdate > getdate())
						AND bicr.SequenceNo = 1)
				,0)
			,BudgetStartDate = BudgetStart.StartDate
			,BudgetEndDate = BudgetEnd.EndDate
			,BudgetYear = IsNull((select top 1 byr.year from AgrBudget byr
					 where bcv.Id = byr.AgrBudgetContainerViewId 
						and byr.AgrBudgetTypeId = 1  
						and IsNull(byr.AgrFundAgreeMapId,0) = IsNull(f.Id,0)
						and byr.startdate = (select min(byr1.startdate) 
		 									from AgrBudget byr1 
											where byr1.AgrBudgetContainerViewId = bcv.Id 
												and IsNull(byr1.AgrFundAgreeMapId,0) = IsNull(byr.AgrFundAgreeMapId ,0)
												and byr1.StartDate is not null
												and byr1.startdate > getdate())
					),0)
			,ICBasis = IsNull(ICBase.[Code],'MTDC')
			,ICBaseTypeId = IsNull(ICBase.[Id],1)
		FROM AgrAgreement_fct agf
		INNER JOIN AgrAgreement aa							ON aa.[Id] = agf.agreementid
		LEFT OUTER JOIN AgrFund_AgrAgreement_Map f			ON agf.[fundId] = f.AgrfundId  
		LEFT OUTER JOIN AgrBudgetContainer bc				ON aa.AgrBudgetContainerId = bc.Id
		LEFT OUTER JOIN finicbasetype icbase				ON icbase.id = bc.indirectcostbaseid
		LEFT OUTER JOIN AgrBudgetContainerView bcv			ON bc.Id = bcv.AgrBudgetContainerId 
		LEFT OUTER JOIN agrbudget agb 						ON agb.AgrBudgetContainerViewId = bcv.Id and IsNull(agb.AgrFundAgreeMapId,0) = IsNull(f.Id,0)
		LEFT OUTER JOIN (select  bs.AgrBudgetContainerViewId ,bs.AgrBudgetTypeId ,bs.AgrFundAgreeMapId ,min(bs.startdate) AS StartDate 
						 from AgrBudget bs where bs.IsAdjustment = 1 and bs.startdate is not null
						 group by bs.AgrBudgetContainerViewId, bs.AgrBudgetTypeId ,bs.AgrFundAgreeMapId) BudgetStart	
															ON BudgetStart.AgrBudgetContainerViewId = bcv.Id 
																and IsNull(BudgetStart.AgrFundAgreeMapId,0) = IsNull(f.Id,0)
		LEFT OUTER JOIN (select  bs.AgrBudgetContainerViewId,bs.AgrBudgetTypeId, bs.AgrFundAgreeMapId, max(bs.enddate) AS EndDate 
						 from AgrBudget bs where bs.IsAdjustment = 1  and bs.enddate is not null
						 group by bs.AgrBudgetContainerViewId, bs.AgrBudgetTypeId ,bs.AgrFundAgreeMapId) BudgetEnd
															ON BudgetEnd.AgrBudgetContainerViewId = bcv.Id 
																and IsNull(BudgetEnd.AgrFundAgreeMapId,0) = IsNull(f.Id,0)
		where 
			bcv.AgrBudgetViewTypeId = 1 -- Pending view of budget
			AND agb.IsAdjustment = 1 -- Must not be an adjustment budget
			and BudgetStart.AgrBudgetTypeId = 1 -- annual budget
			and BudgetEnd.AgrBudgetTypeId = 1 -- annual budget
			and bc.agrBudgetTemplateTypeId = 1 -- Agreement Budget template type
			and agf.BudgetYear = 0
		/*
		>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
		U P D A T E  A W A R D E D  A G R E E M E N T S
		>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
		*/
		Update
			agf
		Set
			BudgetStartDate = IsNull((select top 1 byr.startDate from AgrBudget byr
					 where bcv.Id = byr.AgrBudgetContainerViewId 
						and byr.AgrBudgetTypeId = 1  
						and byr.AgrFundAgreeMapId = f.Id
						and byr.IsAdjustment = 0
						and byr.[Year] = agf.[BudgetYear]),agf.BudgetStartDate)
			,BudgetEndDate = IsNull((select top 1 byr1.EndDate from AgrBudget byr1
					 where bcv.Id = byr1.AgrBudgetContainerViewId 
						and byr1.AgrBudgetTypeId = 1  
						and byr1.AgrFundAgreeMapId = f.Id
						and byr1.IsAdjustment = 0
						and byr1.[Year] = agf.[BudgetYear]),agf.BudgetEndDate)
			,ICBasis = IsNull(ICBase.[Code],'MTDC')
			,ICBaseTypeId = IsNull(ICBase.[Id],1)
		FROM AgrAgreement_fct agf
		INNER JOIN AgrAgreement aa							ON aa.[Id] = agf.agreementid
		LEFT OUTER JOIN AgrFund_AgrAgreement_Map f			ON agf.[fundId] = f.AgrfundId 
		LEFT OUTER JOIN AgrBudgetContainer bc				ON aa.AgrBudgetContainerId = bc.Id
		LEFT OUTER JOIN finicbasetype icbase				ON icbase.id = bc.indirectcostbaseid
		LEFT OUTER JOIN AgrBudgetContainerView bcv			ON bc.Id = bcv.AgrBudgetContainerId
		LEFT OUTER JOIN agrbudget agb 						ON agb.AgrBudgetContainerViewId = bcv.Id and agb.AgrFundAgreeMapId = f.Id
		where 
			bcv.AgrBudgetViewTypeId in (3) -- Pending and Fully Executed/Awarded view of budget
			and bc.agrBudgetTemplateTypeId = 1 -- Agreement Budget template type
			and agb.IsAdjustment = 0 -- Must not be an adjustment budget
		--	and agf.foldernumber = '2002A009449'
		--	and agf.fundid = 13922


		CREATE  INDEX [IX_AgrAgreement_Fct_ResourceId] ON [dbo].[AgrAgreement_Fct]([ResourceId]) ON [PRIMARY]

		
		 

		 CREATE  INDEX [IX_AgrAgreement_Fct_PrincipalInvestigatorId] ON [dbo].[AgrAgreement_Fct]([PrincipalInvestigatorId]) ON [PRIMARY]

		

		 

		 CREATE  INDEX [IX_AgrAgreement_Fct_FundId] ON [dbo].[AgrAgreement_Fct]([FundId]) ON [PRIMARY]

		

		 

		 CREATE  INDEX [IX_AgrAgreement_Fct_FolderNumber] ON [dbo].[AgrAgreement_Fct]([FolderNumber]) ON [PRIMARY]

		

		 

		 CREATE  INDEX [IX_AgrAgreement_Fct_FacilityId] ON [dbo].[AgrAgreement_Fct]([FacilityId]) ON [PRIMARY]

		

		 

		 CREATE  INDEX [IX_AgrAgreement_Fct_WalkerNumber] ON [dbo].[AgrAgreement_Fct]([WalkerNumber]) ON [PRIMARY]

		

		 

		 CREATE  INDEX [IX_AgrAgreement_Fct_BICSNumber] ON [dbo].[AgrAgreement_Fct]([BICSNumber]) ON [PRIMARY]

		

		 

		 CREATE  INDEX [IX_AgrAgreement_Fct_SponsorId] ON [dbo].[AgrAgreement_Fct]([SponsorId]) ON [PRIMARY]

		

		 

		 CREATE  INDEX [IX_AgrAgreement_Fct_BudgetStartDate] ON [dbo].[AgrAgreement_Fct]([BudgetStartDate]) ON [PRIMARY]

		

		 

		 CREATE  INDEX [IX_AgrAgreement_Fct_BudgetEndDate] ON [dbo].[AgrAgreement_Fct]([BudgetEndDate]) ON [PRIMARY]

		

		 

		 CREATE  INDEX [IX_AgrAgreement_Fct_OrganizationId] ON [dbo].[AgrAgreement_Fct]([OrganizationId]) ON [PRIMARY]

		

		 

		 CREATE  INDEX [IX_AgrAgreement_Fct_ActivityTypeId] ON [dbo].[AgrAgreement_Fct]([ActivityTypeId]) ON [PRIMARY]

		

		 

		 CREATE  INDEX [IX_AgrAgreement_Fct_PSActivityCode] ON [dbo].[AgrAgreement_Fct]([PSActivityCode]) ON [PRIMARY]

		

		 

		 CREATE  INDEX [IX_AgrAgreement_Fct_SponsorTypeId] ON [dbo].[AgrAgreement_Fct]([SponsorTypeId]) ON [PRIMARY]

		

		 

		 CREATE  INDEX [IX_AgrAgreement_Fct_SponsorGroupTypeId] ON [dbo].[AgrAgreement_Fct]([SponsorGroupTypeId]) ON [PRIMARY]

		

		 

		 CREATE  INDEX [IX_AgrAgreement_Fct_FundStatusTypeId] ON [dbo].[AgrAgreement_Fct]([FundStatusTypeId]) ON [PRIMARY]

		

		 

		 CREATE  INDEX [IX_AgrAgreement_Fct_ProjectStartDate] ON [dbo].[AgrAgreement_Fct]([ProjectStartDate]) ON [PRIMARY]

		

		 

		 CREATE  INDEX [IX_AgrAgreement_Fct_ProjectEndDate] ON [dbo].[AgrAgreement_Fct]([ProjectEndDate]) ON [PRIMARY]

		

		 

		 CREATE  INDEX [IX_AgrAgreement_Fct_StatusTypeId] ON [dbo].[AgrAgreement_Fct]([StatusTypeId]) ON [PRIMARY]

		

		/*
		>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
		C L E A N U P  D U P L I C A T E  F U N D S
		Preventing duplicate fund instances in the agreement fact table will prevent financials from
		being multiplied by the number of duplicate rows.  This will prevent 
		If a fund appears more than once, it is usually caused by one of the following data problems:
		1) Fund appears on more than 1 agreement
		2) The agreement has a data problem that results in an extra row in one of the join tables
		   used by the insert statement above.
		3) Bug in the join logic of the insert statement above.
		>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
		*/

		Declare @duplicateFunds integer

		select @duplicateFunds = count(*) from agragreement_fct af
		inner join
			(select af1.fundnumber,count(*) as recCount 
			from agragreement_fct af1
			where af1.fundnumber is not null
			group by af1.fundnumber
			having count(*)>1) Dups
		on dups.fundnumber = af.fundnumber
		where 
			af.[Id] <> (Select min(af2.[Id]) from agragreement_fct af2 where af2.fundnumber = af.fundnumber)


		delete af
		from agragreement_fct af
		inner join
			(select af1.fundnumber,count(*) as recCount 
			from agragreement_fct af1
			where af1.fundnumber is not null
			group by af1.fundnumber
			having count(*)>1) Dups
		on dups.fundnumber = af.fundnumber
		where 
			af.[Id] <> (Select min(af2.[Id]) from agragreement_fct af2 where af2.fundnumber = af.fundnumber)

		--if @duplicateFunds<>0 raiserror('Cleaned %d Funds with duplicate rows.',16,1,@duplicateFunds)
	
End


GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Altering [dbo].[GetSalariesOverview]'
GO
SET QUOTED_IDENTIFIER ON
GO



/************************************************************************************************
* Name:		GetSalariesOverview                                                                 
* Purpose:	Stored procedure for retrieving Salaries Overview and Salary Details information.
		If FundNumber is passed, then Salary Details information is retrieved.
		Otherwise retrieve Salaries Overview information.
* PARAMETERS  
*	Name			Description
* -------------------------	-----------------------------
* @domainUserId			Domain User Id
* @fundId			Fund Id
* @employeeJobMapID		Employee Job MapId
* @endDate			the End date of the month.
* @accountID			Account Id.
*@categoryID			Category Id
* ERRORS USED
* Number			Description
*------------------------	--------------------------------
* n/a
* Result Set:	                   												   
*-----------------------------------------------------------------------------------------------
*	Name			Description				
*-----------------------------------------------------------------------------------------------
*	n/a
*
* RETURN VALUE
*	Name			Description
* ----------------------		---------------------------
************************************************************************************************/
--------------------------------------------------------------------
--Modifications:
--09-04-2007	Performance improvements: introduce (nolock)
--------------------------------------------------------------------
ALTER PROCEDURE [dbo].[GetSalariesOverview]
(
	 @sessionID 				VARCHAR(100)
	,@domainUserID 				INTEGER						--1)
	,@includeProgramProjects 	BIT = NULL					--2)
	,@fundNumber 				VARCHAR(8) = NULL			--3)
	,@folderNumber 				VARCHAR(16) = NULL			--4)
	,@bicsNumber 				VARCHAR(10) = NULL			--5)
	,@walkerNumber 				VARCHAR(10) = NULL			--6)
	,@sponsorNumber 			VARCHAR(32) = NULL			--7)
	,@sponsorName 				VARCHAR(64) = NULL			--8)
	,@sponsorTypeId				INTEGER = NULL				--9)
	,@agreementTypeId 			INTEGER = NULL				--10)
	,@activityCode	 			VARCHAR(4)= NULL 			--11)
	,@locationId 				INTEGER = NULL				--12)
	,@budgetStartDate 			DATETIME = NULL				--13)
	,@budgetEndDate 			DATETIME = NULL				--14)
    ,@projectStartDate 			DATETIME = NULL				--15)
	,@projectEndDate 			DATETIME = NULL				--16)
	,@piId						INTEGER = NULL				--17)
	,@chiefCodeList				VARCHAR(1000) = NULL		--18)
	,@sponsorGroupTypeId		INTEGER = NULL				--19)
	,@budgetEndingDays			INTEGER = NULL				--20)
	,@projectEndingDays			INTEGER = NULL				--21)
	,@fundCreatedDays   		integer = NULL				--22)   
	,@lowBalance				DECIMAL(17,2) = NULL		--23)
	,@highBalance				DECIMAL(17,2) = NULL		--24)
	,@agreementStatusTypeList 	VARCHAR(50)= NULL			--25)
	,@fundStatusTypeId 			INTEGER	= NULL				--26
	,@CurrentDateTime			DATETIME = NULL				--27)
	,@firstName					VARCHAR(128) = NULL			--28)
	,@lastName					VARCHAR(128) = NULL			--29)
	,@lastGLFeedRunDate 		DATETIME					--30)
	-- Search in Salaries Overview Page
	,@employeeID				VARCHAR(12) = NULL			--31)
	,@payDateFrom				DATETIME = NULL				--32)
	,@payDateTo					DATETIME = NULL				--33)
	-- Used in Salary Details Page
	,@incomingFundNumber		VARCHAR(8)= NULL			--34)
)
AS
BEGIN
	SET NOCOUNT ON
	
	--set defaults
	SET @includeProgramProjects = IsNull(@includeProgramProjects,0)
	SET @fundNumber = IsNull(@fundNumber,'')
	SET @folderNumber = IsNull(@folderNumber,'')
	SET @bicsNumber = IsNull(@bicsNumber,'')
	SET @walkerNumber = IsNull(@walkerNumber,'')
	SET @sponsorNumber = IsNull(@sponsorNumber,'')
	SET @sponsorName = IsNull(@sponsorName,'')
	SET @sponsorTypeId = IsNull(@sponsorTypeId,0)
	SET @agreementTypeId = IsNull(@agreementTypeId,0)
	SET @activityCode = IsNull(@activityCode,'')
	SET @locationId = IsNull(@locationId,0)
	SET @budgetStartDate = IsNull(@budgetStartDate,'01/01/1900')
	SET @budgetEndDate = IsNull(@budgetEndDate,'01/01/1900')
	SET @projectStartDate = IsNull(@projectStartDate,'01/01/1900')
	SET @projectEndDate = IsNull(@projectEndDate,'01/01/1900')
	SET @piId = IsNull(@piId,0)
	SET @chiefCodeList = IsNull(@chiefCodeList,'')
	SET @sponsorGroupTypeId = IsNull(@sponsorGroupTypeId,0)
	SET @budgetEndingDays = IsNull(@budgetEndingDays,0)
	SET @projectEndingDays = IsNull(@projectEndingDays,0)
	SET @fundCreatedDays = IsNull(@fundCreatedDays,0)
	SET @lowBalance = IsNull(@lowBalance,-922337203685477)
	SET @highBalance = IsNull(@highBalance,922337203685477)
	SET @agreementStatusTypeList = IsNull(@agreementStatusTypeList,'')
	SET @fundStatusTypeId = IsNull(@fundStatusTypeId,0)
	SET @CurrentDateTime = IsNull(@CurrentDateTime,GETDATE())
	SET @incomingFundNumber = IsNull(@incomingFundNumber, '')
	
	DECLARE @journalStartDate 		DATETIME
	DECLARE @fiscalYearStartDate	 	DATETIME
	DECLARE @fiscalYearDays			MONEY
	DECLARE @fiscalYearEndDate	 	DATETIME
	DECLARE @yearStartDate 			VARCHAR(6)
	DECLARE @yearEndDate 			VARCHAR(6)
	DECLARE @fiscalYear 			VARCHAR(4)

	DECLARE @domainTypeID 	INTEGER
	DECLARE @institutionTypeID		INTEGER
	DECLARE @departmentTypeID		INTEGER
	DECLARE	@unitID				INTEGER
	DECLARE @budgetViewTypeID		INTEGER

	SET @domainTypeID = 1
	SET @institutionTypeID = 2
	SET @departmentTypeID = 3
	SET @unitID = 4
	SET @budgetViewTypeID =4

	DECLARE @salaryPayType INTEGER
	SET @salaryPayType = 2
	DECLARE @monthlyPayFrequencyType INTEGER
	SET @monthlyPayFrequencyType = 3
	DECLARE @hrManagementTypeNonManaged INTEGER
	SET @hrManagementTypeNonManaged = 3
	DECLARE @isTracked INTEGER
	SET @isTracked = 1

	
	SET @journalStartDate = DATEADD(DD, 1, @lastGLFeedRunDate)
	
	SET @yearStartDate = '10/01/'	
	SET @yearEndDate = '09/30/'	

	SET @fiscalYear = CAST(DATEPART(YEAR, @journalStartDate) AS VARCHAR)
	IF DATEPART(MONTH, @journalStartDate) <= 9 
		BEGIN
		SET @fiscalYearStartDate = @yearStartDate + cast((cast(@fiscalYear as int)-1) as varchar(4)) 
		SET @fiscalYearEndDate = @yearEndDate + @fiscalYear
		END
	ELSE
		BEGIN
		SET @fiscalYearStartDate = @yearStartDate + @fiscalYear
		SET @fiscalYear = @fiscalYear + 1
		SET @fiscalYearEndDate = @yearEndDate + @fiscalYear 
		END

	SET @fiscalYearDays = convert(money,IsNull(datediff(d,@fiscalYearStartDate,@fiscalYearEndDate)+1,365))

	DECLARE @projectEndingDate DATETIME
	DECLARE @today DATETIME
	SET @today = CAST(DATEPART(MONTH,@CurrentDateTime) AS VARCHAR) 
		+ '/' + CAST(DATEPART(DAY,@CurrentDateTime) AS VARCHAR) 
		+ '/' + CAST(DATEPART(YEAR,@CurrentDateTime) AS VARCHAR) 	
	
	-- If projectEndingDays =0, set it to default end date.[Retrieve all the Records]
	-- otherwise 
	-- Get the records for the specified Project End date.[Project ending in 30/60/90 days]
	IF @projectEndingDays = 0
		SET @projectEndingDate = '12/31/9999'
	ELSE
		SET @projectEndingDate = DATEADD(DAY, @projectEndingDays, @today) 	
	
	DECLARE @viewSalaryInfoBitValue int
	SET @viewSalaryInfoBitValue = 8

		-- Retrieve Salaries Overview Information for non-managed Employees
		
	IF OBJECT_ID('tempdb..#TempFundCollection') is not null drop table #TempFundCollection
	create table #TempFundCollection (FundID int not null, AccessLevel int not null)

	If (@incomingFundNumber = '') begin
		exec GetFundCollection @SessionId, @domainUserID, @viewSalaryInfoBitValue
	end
	else
	Begin
		INSERT INTO #TempFundCollection
		Select af.FundId, urc.AccessLevel From AgrAgreement_fct af (nolock)
		Inner join UserResourceCache urc (nolock) on urc.ResourceId = af.ResourceId
		Where af.FundNumber = @incomingFundNumber and urc.FwkDomainUserId = @DomainUserId
		and (@viewSalaryInfoBitValue & urc.AccessLevel) > 0
	End
	
	--Create Unique Index FundId on #TempFundCollection (FundId)


If (@payDateFrom IS NULL and @payDateTo IS NULL)
Begin
			SELECT	
				psd.LastName,
				psd.FirstName,
				psd.FundNumber,
				psd.AnnualRate,
				psd.StartDate,
				psd.EndDate,
				psd.PerEmployeeJobMapId,
				psd.MonthlyRate AS 'MonthlyRate',
				psd.MonthsRemaining AS 'MonthsRemaining',
				psd.CommittedSalary AS 'CommittedSalary',
				psd.FringeRate AS 'FringeRate',
				psd.CommittedFringe AS 'CommittedFringe',
				psd.TotalCommitted AS 'TotalCommitted',
				psd.ExpenseAmount AS 'PaidToDate',
				psd.PercentEffort AS 'TrackedEffort',
				psd.PercentageEffort AS 'SponsorEffort'	
		FROM			
			PerSalaryDistributionSrc_Fct psd (nolock)
		INNER JOIN
			#TempFundCollection f
		ON
			psd.FundId = f.FundID	

		
			WHERE
				(@firstName IS NULL OR psd.FirstName LIKE @firstName + '%')
			AND
				(@lastName IS NULL OR psd.LastName LIKE @lastName + '%')
			AND
				(@employeeID IS NULL OR psd.EmployeeNumber like @employeeID + '%')
			AND
				psd.ProjectEndDate <= @projectEndingDate
			-- Removes duplicate agreements due to multiple funds on the agreement. 

		UNION ALL
			-- Retrieve Salary Overview Info for Managed Employees
			SELECT	
				pej.LastName,
				pej.FirstName,
				aaf.FundNumber,
				sd.AnnualRate,
				Effective.StartDate,
				Effective.EndDate,
				sd.PerEmployeeJobMapId,
				sd.AnnualRate/12 AS 'MonthlyRate',
				CONVERT(DECIMAL(12,7), Effective.Days) * 12/@fiscalYearDays AS 'MonthsRemaining',
				(sd.AnnualRate/12 * (CONVERT(DECIMAL(12,7), CONVERT(DECIMAL(12,7), Effective.Days)*12/@fiscalYearDays))) AS 'CommittedSalary',
				ISNULL(pej.FringeRate,0) AS 'FringeRate',
				(sd.AnnualRate/12 * (CONVERT(DECIMAL(12,7),CONVERT(DECIMAL(12,7), Effective.Days)*12/@fiscalYearDays)*(pej.FringeRate))) AS 'CommittedFringe',
				(sd.AnnualRate/12 * (CONVERT(DECIMAL(12,7),CONVERT(DECIMAL(12,7), Effective.Days)*12/@fiscalYearDays)) + 
				(sd.AnnualRate/12 * (CONVERT(DECIMAL(12,7),CONVERT(DECIMAL(12,7), Effective.Days)*12/@fiscalYearDays))*(pej.FringeRate))) AS 'TotalCommitted',
				ISNULL(sts.ExpenseAmount,0) AS 'PaidToDate',
				ISNULL(sd.PercentEffort, 0) AS 'TrackedEffort'	
				,ISNULL(aspey.PercentageEffort, 0) AS 'SponsorEffort'		
			FROM			
				PerSalaryDistribution sd (nolock)
			INNER JOIN
				#TempFundCollection f
			ON
				sd.AgrFundId = f.FundID	
			INNER JOIN
				AgrAgreement_Fct aaf (nolock)
			ON
				f.FundID = aaf.FundID
			INNER JOIN		
				PerEmployeeJob_Fct pej (nolock)
			ON
				pej.[JobMapID] = sd.PerEmployeeJobMapId
		LEFT OUTER JOIN
			PersalaryTransactionSrc_Fct sts (nolock)
		ON
			f.FundID = sts.FundID
		AND
			pej.AdmInternalPersonID = sts.AdmInternalPersonID
		
		LEFT OUTER JOIN  
			SvcEntity_AdmStaffedPerson_Map seaspm (nolock)
		ON
			pej.[AdmPersonID] = seaspm.AdmPersonId
		AND
			aaf.SvcEntityID = seaspm.SvcEntityID

		LEFT OUTER JOIN	
			AgrStaffedPersonEffortYear aspey (nolock)
		ON				
			seaspm.[ID] = aspey.SvcEntityStaffedPersonMapId
		AND
			aspey.SequenceYear = aaf.budgetYear
		AND
			 aspey.AgrBudgetViewTypeId  = @budgetViewTypeID
		-- remove duplicates staff person year rows.
		AND aspey.[Id] = (SELECT MAX(aspey1.[Id]) FROM AgrStaffedPersonEffortYear aspey1 (nolock)
			WHERE 	seaspm.[Id] = aspey1.SvcEntityStaffedPersonMapId 
			AND aspey1.SequenceYear = aaf.budgetYear
			AND  aspey1.AgrBudgetViewTypeId =@budgetViewTypeID )
			
		INNER JOIN
			(SELECT 
				aaf1.FundId
				,sd1.[ID]
				,CASE
					-- Handle projects that are not approved that end before fye
					WHEN aaf1.BudgetEndDate < @journalStartDate
						AND aaf1.ProjectEndDate >= @journalStartDate
						AND @fiscalYearEndDate > aaf1.ProjectEndDate THEN
						CASE
							WHEN sd1.EffectiveDate <= @journalStartDate 
								 AND sd1.ExpirationDate >= @journalStartDate 
								 AND (sd1.ExpirationDate <= aaf1.ProjectEndDate 
									or (aaf1.BudgetEndDate = aaf1.ProjectEndDate)) THEN 
								datediff(dd, @journalStartDate
										, case when sd1.ExpirationDate < @fiscalYearEndDate then
												sd1.ExpirationDate Else @fiscalYearEndDate End) + 1
					
							WHEN sd1.EffectiveDate <= @journalStartDate 
								 AND sd1.ExpirationDate >= aaf1.ProjectEndDate  THEN 
								datediff(dd, @journalStartDate, aaf1.ProjectEndDate)+1
								
							WHEN sd1.EffectiveDate >= @journalStartDate
								 AND sd1.EffectiveDate <= aaf1.ProjectEndDate
								 AND (sd1.ExpirationDate <= aaf1.ProjectEndDate 
										or (aaf1.BudgetEndDate = aaf1.ProjectEndDate)) THEN 
								datediff(dd, sd1.EffectiveDate
										, case when sd1.ExpirationDate < @fiscalYearEndDate then
												sd1.ExpirationDate Else @fiscalYearEndDate End) + 1
								
 							WHEN sd1.EffectiveDate >= @journalStartDate
 								 AND sd1.EffectiveDate <= aaf1.ProjectEndDate
 								 AND sd1.ExpirationDate >= aaf1.ProjectEndDate THEN 
							datediff(dd, sd1.EffectiveDate, aaf1.ProjectEndDate) + 1

						END
		
					-- Handle projects that are not approved that end after fye
					WHEN aaf1.BudgetEndDate < @journalStartDate
						AND aaf1.ProjectEndDate >= @journalStartDate
						AND @fiscalYearEndDate < aaf1.ProjectEndDate THEN
		
						CASE
							WHEN sd1.EffectiveDate <= @journalStartDate 
								 AND sd1.ExpirationDate >= @journalStartDate 
								 AND (sd1.ExpirationDate <= @fiscalYearEndDate 
										or (aaf1.BudgetEndDate = aaf1.ProjectEndDate)) THEN 
								datediff(dd,@journalStartDate
										, case when sd1.ExpirationDate < @fiscalYearEndDate then
												sd1.ExpirationDate Else @fiscalYearEndDate End) + 1
					
							WHEN sd1.EffectiveDate <= @journalStartDate 
								 AND sd1.ExpirationDate >= @fiscalYearEndDate  THEN 
								datediff(dd,@journalStartDate, @fiscalYearEndDate) + 1
								
							WHEN sd1.EffectiveDate >= @journalStartDate
								 AND sd1.EffectiveDate <= @fiscalYearEndDate
								 AND (sd1.ExpirationDate <= @fiscalYearEndDate 
										or (aaf1.BudgetEndDate = aaf1.ProjectEndDate)) THEN 
								datediff(dd, sd1.EffectiveDate
										, case when sd1.ExpirationDate < @fiscalYearEndDate then
												sd1.ExpirationDate Else @fiscalYearEndDate End) + 1
								
	 						WHEN sd1.EffectiveDate >= @journalStartDate
	 								 AND sd1.EffectiveDate <= @fiscalYearEndDate
	 								 AND sd1.ExpirationDate >= @fiscalYearEndDate THEN 
								datediff(dd, sd1.EffectiveDate, @fiscalYearEndDate) + 1
						END
		
					-- Handle regular projects
					ELSE
						CASE
		
							WHEN sd1.EffectiveDate <= @journalStartDate 
								 AND sd1.ExpirationDate >= @journalStartDate 
								 AND (sd1.ExpirationDate <= aaf1.BudgetEndDate 
										or (aaf1.BudgetEndDate = aaf1.ProjectEndDate)) THEN 
								datediff(dd, @journalStartDate
										, case when sd1.ExpirationDate < @fiscalYearEndDate then
											case when sd1.ExpirationDate < aaf1.BudgetEndDate  
												or aaf1.BudgetEndDate < @journalStartDate then
													sd1.ExpirationDate
												Else aaf1.BudgetEndDate 
											End
										Else 
											case when @fiscalYearEndDate < aaf1.BudgetEndDate 
														or aaf1.BudgetEndDate < @journalStartDate then
													@fiscalYearEndDate
												Else aaf1.BudgetEndDate 
											End
										End) + 1
					
							WHEN sd1.EffectiveDate <= @journalStartDate 
								 AND sd1.ExpirationDate >= aaf1.BudgetEndDate  THEN 
								datediff(dd,@journalStartDate, aaf1.BudgetEndDate) + 1
								
							WHEN sd1.EffectiveDate >= @journalStartDate
								 AND sd1.EffectiveDate <= aaf1.BudgetEndDate
								 AND (sd1.ExpirationDate <= aaf1.BudgetEndDate 
										or (aaf1.BudgetEndDate = aaf1.ProjectEndDate)) THEN 
								datediff(dd, sd1.EffectiveDate
										, case when sd1.ExpirationDate < @fiscalYearEndDate then
											case when sd1.ExpirationDate < aaf1.BudgetEndDate  
												or aaf1.BudgetEndDate < @journalStartDate then
													sd1.ExpirationDate
												Else aaf1.BudgetEndDate 
											End
										Else 
											case when @fiscalYearEndDate < aaf1.BudgetEndDate 
														or aaf1.BudgetEndDate < @journalStartDate then
													@fiscalYearEndDate
												Else aaf1.BudgetEndDate 
											End
										End) + 1
								
	 						WHEN sd1.EffectiveDate >= @journalStartDate
	 								 AND sd1.EffectiveDate <= aaf1.BudgetEndDate
	 								 AND sd1.ExpirationDate >= aaf1.BudgetEndDate THEN 
									datediff(dd, sd1.EffectiveDate, aaf1.BudgetEndDate) + 1
						END
				END AS 'Days'
				,CASE
					-- Handle projects that are not approved that end before fye
					WHEN aaf1.BudgetEndDate < @journalStartDate
						AND aaf1.ProjectEndDate >= @journalStartDate
						AND @fiscalYearEndDate > aaf1.ProjectEndDate THEN
		
						CASE
							WHEN sd1.EffectiveDate <= @journalStartDate 
								 AND sd1.ExpirationDate >= @journalStartDate 
								 AND (sd1.ExpirationDate <= aaf1.ProjectEndDate 
										or (aaf1.BudgetEndDate = aaf1.ProjectEndDate)) THEN 
									@journalStartDate
		
							WHEN sd1.EffectiveDate <= @journalStartDate 
								 AND sd1.ExpirationDate >= aaf1.ProjectEndDate  THEN @journalStartDate
								
							WHEN sd1.EffectiveDate >= @journalStartDate
								 AND sd1.EffectiveDate <= aaf1.ProjectEndDate
								 AND (sd1.ExpirationDate <= aaf1.ProjectEndDate 
										or (aaf1.BudgetEndDate = aaf1.ProjectEndDate)) THEN 
									sd1.EffectiveDate
								
	 						WHEN sd1.EffectiveDate >= @journalStartDate
	 								 AND sd1.EffectiveDate <= aaf1.ProjectEndDate
	 								 AND sd1.ExpirationDate >= aaf1.ProjectEndDate THEN 
								sd1.EffectiveDate
						END
		
					-- Handle projects that are not approved that end after fye
					WHEN aaf1.BudgetEndDate < @journalStartDate
						AND aaf1.ProjectEndDate >= @journalStartDate
						AND @fiscalYearEndDate < aaf1.ProjectEndDate THEN
		
						CASE
							WHEN sd1.EffectiveDate <= @journalStartDate 
								 AND sd1.ExpirationDate >= @journalStartDate 
								 AND (sd1.ExpirationDate <= @fiscalYearEndDate 
										or (aaf1.BudgetEndDate = aaf1.ProjectEndDate)) THEN 
								@journalStartDate
		
							WHEN sd1.EffectiveDate <= @journalStartDate 
								 AND sd1.ExpirationDate >= @fiscalYearEndDate  THEN @journalStartDate
								
							WHEN sd1.EffectiveDate >= @journalStartDate
								 AND sd1.EffectiveDate <= @fiscalYearEndDate
								 AND (sd1.ExpirationDate <= @fiscalYearEndDate
										or (aaf1.BudgetEndDate = aaf1.ProjectEndDate)) THEN 
								sd1.EffectiveDate
								
	 						WHEN sd1.EffectiveDate >= @journalStartDate
	 								 AND sd1.EffectiveDate <= @fiscalYearEndDate
	 								 AND sd1.ExpirationDate >= @fiscalYearEndDate THEN 
								sd1.EffectiveDate
						END
		
					-- Handle regular projects
					ELSE
		
						CASE
							WHEN sd1.EffectiveDate <= @journalStartDate 
								 AND sd1.ExpirationDate >= @journalStartDate 
								 AND (sd1.ExpirationDate <= aaf1.BudgetEndDate 
										or (aaf1.BudgetEndDate = aaf1.ProjectEndDate)) THEN 
								@journalStartDate
		
							WHEN sd1.EffectiveDate <= @journalStartDate 
								 AND sd1.ExpirationDate >= aaf1.BudgetEndDate  THEN @journalStartDate
								
							WHEN sd1.EffectiveDate >= @journalStartDate
								 AND sd1.EffectiveDate <= aaf1.BudgetEndDate
								 AND (sd1.ExpirationDate <= aaf1.BudgetEndDate 
										or (aaf1.BudgetEndDate = aaf1.ProjectEndDate)) THEN 
								sd1.EffectiveDate
								
	 							WHEN sd1.EffectiveDate >= @journalStartDate
	 								 AND sd1.EffectiveDate <= aaf1.BudgetEndDate
	 								 AND sd1.ExpirationDate >= aaf1.BudgetEndDate THEN
								sd1.EffectiveDate
						END
				END AS 'StartDate'
				,CASE
					-- Handle projects that are not approved that end before fye
					WHEN aaf1.BudgetEndDate < @journalStartDate
						AND aaf1.ProjectEndDate >= @journalStartDate
						AND @fiscalYearEndDate > aaf1.ProjectEndDate THEN
		
						CASE
							WHEN sd1.EffectiveDate <= @journalStartDate 
								 AND sd1.ExpirationDate >= @journalStartDate 
								 AND (sd1.ExpirationDate <= aaf1.ProjectEndDate 
										or (aaf1.BudgetEndDate = aaf1.ProjectEndDate)) THEN 
								case when sd1.ExpirationDate < @fiscalYearEndDate then
										sd1.ExpirationDate Else @fiscalYearEndDate End
		
							WHEN sd1.EffectiveDate <= @journalStartDate 
								 AND sd1.ExpirationDate >= aaf1.ProjectEndDate  THEN  
								aaf1.ProjectEndDate
								
							WHEN sd1.EffectiveDate >= @journalStartDate
								 AND sd1.EffectiveDate <= aaf1.ProjectEndDate
								 AND (sd1.ExpirationDate <= aaf1.ProjectEndDate 
										or (aaf1.BudgetEndDate = aaf1.ProjectEndDate)) THEN 
								case when sd1.ExpirationDate < @fiscalYearEndDate then
										sd1.ExpirationDate Else @fiscalYearEndDate End
								
	 						WHEN sd1.EffectiveDate >= @journalStartDate
	 								 AND sd1.EffectiveDate <= aaf1.ProjectEndDate
	 								 AND sd1.ExpirationDate >= aaf1.ProjectEndDate THEN 
								aaf1.ProjectEndDate
							
						END
		
					-- Handle projects that are not approved that end after fye
					WHEN aaf1.BudgetEndDate < @journalStartDate
						AND aaf1.ProjectEndDate >= @journalStartDate
						AND @fiscalYearEndDate < aaf1.ProjectEndDate THEN
		
						CASE
							WHEN sd1.EffectiveDate <= @journalStartDate 
								 AND sd1.ExpirationDate >=@journalStartDate 
								 AND (sd1.ExpirationDate <= @fiscalYearEndDate 
										or (aaf1.BudgetEndDate = aaf1.ProjectEndDate)) THEN 
								case when sd1.ExpirationDate < @fiscalYearEndDate then
										sd1.ExpirationDate Else @fiscalYearEndDate End
		
							WHEN sd1.EffectiveDate <= @journalStartDate 
								 AND sd1.ExpirationDate >= @fiscalYearEndDate  THEN  
								@fiscalYearEndDate
								
							WHEN sd1.EffectiveDate >= @journalStartDate
								 AND sd1.EffectiveDate <= @fiscalYearEndDate
								 AND (sd1.ExpirationDate <= @fiscalYearEndDate
										or (aaf1.BudgetEndDate = aaf1.ProjectEndDate)) THEN 
								case when sd1.ExpirationDate < @fiscalYearEndDate then
										sd1.ExpirationDate Else @fiscalYearEndDate End
								
	 						WHEN sd1.EffectiveDate >= @journalStartDate
	 								 AND sd1.EffectiveDate <= @fiscalYearEndDate
	 								 AND sd1.ExpirationDate >= @fiscalYearEndDate THEN 
								@fiscalYearEndDate
						END
		
					-- Handle regular projects
					ELSE
		
						CASE
							WHEN sd1.EffectiveDate <= @journalStartDate 
								 AND sd1.ExpirationDate >= @journalStartDate 
								 AND (sd1.ExpirationDate <= aaf1.BudgetEndDate 
										or (aaf1.BudgetEndDate = aaf1.ProjectEndDate)) THEN  
								case 
									when sd1.ExpirationDate < @fiscalYearEndDate then
										case when sd1.ExpirationDate < aaf1.BudgetEndDate  
											or aaf1.BudgetEndDate < @journalStartDate then
												sd1.ExpirationDate
											Else aaf1.BudgetEndDate 
										End
									Else 
										case when @fiscalYearEndDate < aaf1.BudgetEndDate 
													or aaf1.BudgetEndDate < @journalStartDate then
												@fiscalYearEndDate
											Else aaf1.BudgetEndDate 
										End
								End

					
							WHEN sd1.EffectiveDate <= @journalStartDate 
								 AND sd1.ExpirationDate >= aaf1.BudgetEndDate  THEN 
								aaf1.BudgetEndDate
								
							WHEN sd1.EffectiveDate >= @journalStartDate
								 AND sd1.EffectiveDate <= aaf1.BudgetEndDate
								 AND (sd1.ExpirationDate <= aaf1.BudgetEndDate 
										or (aaf1.BudgetEndDate = aaf1.ProjectEndDate)) THEN 
								case 
									when sd1.ExpirationDate < @fiscalYearEndDate then
										case when sd1.ExpirationDate < aaf1.BudgetEndDate  
											or aaf1.BudgetEndDate < @journalStartDate then
												sd1.ExpirationDate
											Else aaf1.BudgetEndDate 
										End
									Else 
										case when @fiscalYearEndDate < aaf1.BudgetEndDate 
													or aaf1.BudgetEndDate < @journalStartDate then
												@fiscalYearEndDate
											Else aaf1.BudgetEndDate 
										End
								End
								
							WHEN sd1.EffectiveDate >= @journalStartDate
	 								 AND sd1.EffectiveDate <= aaf1.BudgetEndDate
	 								 AND sd1.ExpirationDate >= aaf1.BudgetEndDate THEN
								aaf1.BudgetEndDate
						END
		
				END AS 'EndDate'
			FROM 
				PerSalaryDistribution sd1 (nolock)
			INNER JOIN 
				AgrAgreement_Fct aaf1 (nolock) 
			ON
				aaf1.FundId = sd1.AgrFundId
			) Effective
			ON
				Effective.[ID] = sd.[ID]
			WHERE
				sd.AnnualRate > 0 
			AND
				pej.IsTracked = @isTracked
			AND
				(@firstName IS NULL OR pej.FirstName LIKE @firstName + '%')
			AND
				(@lastName IS NULL OR pej.LastName LIKE @lastName + '%')
			AND 
				(effective.Days IS NOT NULL AND effective.Days > 0)
			AND
				(@employeeID IS NULL OR pej.EmployeeNumber like @employeeID + '%')
			AND
				aaf.ProjectEndDate <= @projectEndingDate
			
			
			-- Removes duplicate agreements due to multiple funds on the agreement. 
			AND aaf.[Id] = (SELECT MAX(aaf1.[ID]) FROM agragreement_fct aaf1 (nolock) 
							WHERE aaf1.resourceId =aaf.resourceId and aaf1.FundNumber = aaf.FundNumber)
		
				
			ORDER BY 
				lastname,
				 firstname 
				, fundnumber
				
		END
		Else
Begin
SELECT	
				ap.LastName,
				ap.FirstName,
				aaf.FundNumber,
				sd.AnnualRate,
				Effective.StartDate,
				Effective.EndDate,
				sd.PerEmployeeJobMapId,
				sd.AnnualRate/12 AS 'MonthlyRate',
				CONVERT(DECIMAL(12,7), Effective.Days) * 12/@fiscalYearDays AS 'MonthsRemaining',
				(sd.AnnualRate/12 * (CONVERT(DECIMAL(12,7), CONVERT(DECIMAL(12,7), Effective.Days)*12/@fiscalYearDays))) AS 'CommittedSalary',
				ISNULL(frs.FringeRate,0) AS 'FringeRate',
				(sd.AnnualRate/12 * (CONVERT(DECIMAL(12,7),CONVERT(DECIMAL(12,7), Effective.Days)*12/@fiscalYearDays)*(frs.FringeRate))) AS 'CommittedFringe',
				(sd.AnnualRate/12 * (CONVERT(DECIMAL(12,7),CONVERT(DECIMAL(12,7), Effective.Days)*12/@fiscalYearDays)) + 
				(sd.AnnualRate/12 * (CONVERT(DECIMAL(12,7),CONVERT(DECIMAL(12,7), Effective.Days)*12/@fiscalYearDays))*(frs.FringeRate))) AS 'TotalCommitted',
				SUM(ISNULL(ExpenseAmount,0)) AS 'PaidToDate',
				ISNULL(sd.PercentEffort, 0) AS 'TrackedEffort'	
				,ISNULL(aspey.PercentageEffort, 0) AS 'SponsorEffort'		
		FROM			
			PerSalaryDistribution_src sd (nolock)
		INNER JOIN
			#TempFundCollection f
		ON
			sd.AgrFundId = f.FundID	
		INNER JOIN
			AgrAgreement_Fct aaf (nolock)
		ON
			f.FundID = aaf.FundID
		INNER JOIN		
			PerEmployee_Job_Map ejm (nolock)
		ON
			ejm.[ID] = sd.PerEmployeeJobMapId
		INNER JOIN
			PerHRDepartment hrd (nolock)
		ON
			ejm.PerHRDepartmentID = hrd.ID
		INNER JOIN		
			AdmInternalPerson ip (nolock)
		ON	
			ip.[ID] = ejm.AdmInternalPersonId
		INNER JOIN		
			AdmPerson ap (nolock) 
		ON	
			ap.[ID] = ip.AdmPersonId
		LEFT OUTER JOIN
			PerSalaryTransaction_src sts (nolock)
		ON
			f.FundID = sts.FundID
		AND
			ip.ID = sts.AdmInternalPersonID
		AND
			sts.PayDate <= GETDATE()
		INNER JOIN		
			PerJobType jt (nolock)
		ON	
			jt.[ID] = ejm.PerJobTypeId
		LEFT OUTER JOIN
			PerPayCompany pco (nolock)
		ON
			pco.[Name] = jt.PayCompany
		LEFT OUTER JOIN
			FinAccount_FringeRateStep_Map frsm (nolock)
		ON 	
			frsm.FinaccountId = jt.SalaryAccountId
		AND
			frsm.fwkDomainOrganizationID = ISNULL(pco.InstitutionID, 0) -- Default to MGH if Org is Partners
		-- NOTE: When fringe Rates for Partners are added, the default Institution needs to be removed
		AND frsm.FinFiscalYearId  = (Select MAX(frsm1.FinFiscalYearId) 
									 from FinAccount_FringeRateStep_Map frsm1 (nolock)
									 inner join FinFiscalYear fy1 (nolock) on frsm1.FinFiscalYearId = fy1.[ID]
									 where frsm1.FinaccountId = frsm.FinaccountId
										and frsm1.fwkDomainOrganizationID = frsm.fwkDomainOrganizationID
										and fy1.[Year] <= @fiscalYear)
		LEFT OUTER JOIN
			FinFringeRateStep frs (nolock)
		ON	
			frs.[ID] = frsm.FinFringeRateStepId
		
		LEFT OUTER JOIN  
			SvcEntity_AdmStaffedPerson_Map seaspm (nolock)
		ON
			ap.[ID] = seaspm.AdmPersonId
		AND
			aaf.SvcEntityID = seaspm.SvcEntityID

		LEFT OUTER JOIN	
			AgrStaffedPersonEffortYear aspey (nolock)
		ON				
			seaspm.[ID] = aspey.SvcEntityStaffedPersonMapId
		AND
			aspey.SequenceYear = aaf.budgetYear
		AND
			 aspey.AgrBudgetViewTypeId  = @budgetViewTypeID
			-- remove duplicates staff person year rows.
			AND aspey.[Id] = (SELECT MAX(aspey1.[Id]) FROM AgrStaffedPersonEffortYear aspey1 (nolock)
						WHERE 	seaspm.[Id] = aspey1.SvcEntityStaffedPersonMapId 
						AND aspey1.SequenceYear = aaf.budgetYear
						AND  aspey1.AgrBudgetViewTypeId =@budgetViewTypeID )
		INNER JOIN
			(SELECT 
				aaf1.FundId
				,sd1.[ID]
				,CASE
					-- Handle projects that are not approved that end before fye
					WHEN aaf1.BudgetEndDate < @journalStartDate
						AND aaf1.ProjectEndDate >= @journalStartDate
						AND @fiscalYearEndDate > aaf1.ProjectEndDate THEN

						CASE
							WHEN sd1.EffectiveDate <= @journalStartDate 
								 AND sd1.ExpirationDate >= @journalStartDate 
								 AND (sd1.ExpirationDate <= aaf1.ProjectEndDate 
									or (aaf1.BudgetEndDate = aaf1.ProjectEndDate)) THEN 
								datediff(dd, @journalStartDate
										, case when sd1.ExpirationDate < @fiscalYearEndDate then
												sd1.ExpirationDate Else @fiscalYearEndDate End ) + 1
					
							WHEN sd1.EffectiveDate <= @journalStartDate 
								 AND sd1.ExpirationDate >= aaf1.ProjectEndDate  THEN 
								datediff(dd, @journalStartDate, aaf1.ProjectEndDate)+1
								
							WHEN sd1.EffectiveDate >= @journalStartDate
								 AND sd1.EffectiveDate <= aaf1.ProjectEndDate
								 AND (sd1.ExpirationDate <= aaf1.ProjectEndDate 
										or (aaf1.BudgetEndDate = aaf1.ProjectEndDate)) THEN 
								datediff(dd, sd1.EffectiveDate
										, case when sd1.ExpirationDate < @fiscalYearEndDate then
												sd1.ExpirationDate Else @fiscalYearEndDate End ) + 1
								
 							WHEN sd1.EffectiveDate >= @journalStartDate
 								 AND sd1.EffectiveDate <= aaf1.ProjectEndDate
 								 AND sd1.ExpirationDate >= aaf1.ProjectEndDate THEN 
							datediff(dd, sd1.EffectiveDate, aaf1.ProjectEndDate) + 1

						END
		
					-- Handle projects that are not approved that end after fye
					WHEN aaf1.BudgetEndDate < @journalStartDate
						AND aaf1.ProjectEndDate >= @journalStartDate
						AND @fiscalYearEndDate < aaf1.ProjectEndDate THEN
		
						CASE
							WHEN sd1.EffectiveDate <= @journalStartDate 
								 AND sd1.ExpirationDate >= @journalStartDate 
								 AND (sd1.ExpirationDate <= @fiscalYearEndDate 
										or (aaf1.BudgetEndDate = aaf1.ProjectEndDate)) THEN 
								datediff(dd,@journalStartDate
										, case when sd1.ExpirationDate < @fiscalYearEndDate then
												sd1.ExpirationDate Else @fiscalYearEndDate End ) + 1
					
							WHEN sd1.EffectiveDate <= @journalStartDate 
								 AND sd1.ExpirationDate >= @fiscalYearEndDate  THEN 
								datediff(dd,@journalStartDate, @fiscalYearEndDate) + 1
								
							WHEN sd1.EffectiveDate >= @journalStartDate
								 AND sd1.EffectiveDate <= @fiscalYearEndDate
								 AND (sd1.ExpirationDate <= @fiscalYearEndDate 
										or (aaf1.BudgetEndDate = aaf1.ProjectEndDate)) THEN 
								datediff(dd, sd1.EffectiveDate
										, case when sd1.ExpirationDate < @fiscalYearEndDate then
												sd1.ExpirationDate Else @fiscalYearEndDate End ) + 1
								
	 						WHEN sd1.EffectiveDate >= @journalStartDate
	 								 AND sd1.EffectiveDate <= @fiscalYearEndDate
	 								 AND sd1.ExpirationDate >= @fiscalYearEndDate THEN 
								datediff(dd, sd1.EffectiveDate, @fiscalYearEndDate) + 1
						END
		
					-- Handle regular projects
					ELSE
						CASE
		
							WHEN sd1.EffectiveDate <= @journalStartDate 
								 AND sd1.ExpirationDate >= @journalStartDate 
								 AND (sd1.ExpirationDate <= aaf1.BudgetEndDate 
										or (aaf1.BudgetEndDate = aaf1.ProjectEndDate)) THEN 
								datediff(dd, @journalStartDate
										, case when sd1.ExpirationDate < @fiscalYearEndDate then
											case when sd1.ExpirationDate < aaf1.BudgetEndDate  
												or aaf1.BudgetEndDate < @journalStartDate then
													sd1.ExpirationDate
												Else aaf1.BudgetEndDate 
											End
										Else 
											case when @fiscalYearEndDate < aaf1.BudgetEndDate 
														or aaf1.BudgetEndDate < @journalStartDate then
													@fiscalYearEndDate
												Else aaf1.BudgetEndDate 
											End
										End ) + 1
					
							WHEN sd1.EffectiveDate <= @journalStartDate 
								 AND sd1.ExpirationDate >= aaf1.BudgetEndDate  THEN 
								datediff(dd,@journalStartDate, aaf1.BudgetEndDate) + 1
								
							WHEN sd1.EffectiveDate >= @journalStartDate
								 AND sd1.EffectiveDate <= aaf1.BudgetEndDate
								 AND (sd1.ExpirationDate <= aaf1.BudgetEndDate 
										or (aaf1.BudgetEndDate = aaf1.ProjectEndDate)) THEN 
								datediff(dd, sd1.EffectiveDate
										, case when sd1.ExpirationDate < @fiscalYearEndDate then
											case when sd1.ExpirationDate < aaf1.BudgetEndDate  
												or aaf1.BudgetEndDate < @journalStartDate then
													sd1.ExpirationDate
												Else aaf1.BudgetEndDate 
											End
										Else 
											case when @fiscalYearEndDate < aaf1.BudgetEndDate 
														or aaf1.BudgetEndDate < @journalStartDate then
													@fiscalYearEndDate
												Else aaf1.BudgetEndDate 
											End
										End) + 1
								
	 						WHEN sd1.EffectiveDate >= @journalStartDate
	 								 AND sd1.EffectiveDate <= aaf1.BudgetEndDate
	 								 AND sd1.ExpirationDate >= aaf1.BudgetEndDate THEN 
									datediff(dd, sd1.EffectiveDate, aaf1.BudgetEndDate) + 1
						END
				END AS 'Days'
				,CASE
					-- Handle projects that are not approved that end before fye
					WHEN aaf1.BudgetEndDate < @journalStartDate
						AND aaf1.ProjectEndDate >= @journalStartDate
						AND @fiscalYearEndDate > aaf1.ProjectEndDate THEN
		
						CASE
							WHEN sd1.EffectiveDate <= @journalStartDate 
								 AND sd1.ExpirationDate >= @journalStartDate 
								 AND (sd1.ExpirationDate <= aaf1.ProjectEndDate 
										or (aaf1.BudgetEndDate = aaf1.ProjectEndDate)) THEN 
									@journalStartDate
		
							WHEN sd1.EffectiveDate <= @journalStartDate 
								 AND sd1.ExpirationDate >= aaf1.ProjectEndDate  THEN @journalStartDate
								
							WHEN sd1.EffectiveDate >= @journalStartDate
								 AND sd1.EffectiveDate <= aaf1.ProjectEndDate
								 AND (sd1.ExpirationDate <= aaf1.ProjectEndDate 
										or (aaf1.BudgetEndDate = aaf1.ProjectEndDate)) THEN 
									sd1.EffectiveDate
								
	 						WHEN sd1.EffectiveDate >= @journalStartDate
	 								 AND sd1.EffectiveDate <= aaf1.ProjectEndDate
	 								 AND sd1.ExpirationDate >= aaf1.ProjectEndDate THEN 
								sd1.EffectiveDate
						END
		
					-- Handle projects that are not approved that end after fye
					WHEN aaf1.BudgetEndDate < @journalStartDate
						AND aaf1.ProjectEndDate >= @journalStartDate
						AND @fiscalYearEndDate < aaf1.ProjectEndDate THEN
		
						CASE
							WHEN sd1.EffectiveDate <= @journalStartDate 
								 AND sd1.ExpirationDate >= @journalStartDate 
								 AND (sd1.ExpirationDate <= @fiscalYearEndDate 
										or (aaf1.BudgetEndDate = aaf1.ProjectEndDate)) THEN 
								@journalStartDate
		
							WHEN sd1.EffectiveDate <= @journalStartDate 
								 AND sd1.ExpirationDate >= @fiscalYearEndDate  THEN @journalStartDate
								
							WHEN sd1.EffectiveDate >= @journalStartDate
								 AND sd1.EffectiveDate <= @fiscalYearEndDate
								 AND (sd1.ExpirationDate <= @fiscalYearEndDate
										or (aaf1.BudgetEndDate = aaf1.ProjectEndDate)) THEN 
								sd1.EffectiveDate
								
	 						WHEN sd1.EffectiveDate >= @journalStartDate
	 								 AND sd1.EffectiveDate <= @fiscalYearEndDate
	 								 AND sd1.ExpirationDate >= @fiscalYearEndDate THEN 
								sd1.EffectiveDate
						END
		
					-- Handle regular projects
					ELSE
		
						CASE
							WHEN sd1.EffectiveDate <= @journalStartDate 
								 AND sd1.ExpirationDate >= @journalStartDate 
								 AND (sd1.ExpirationDate <= aaf1.BudgetEndDate 
										or (aaf1.BudgetEndDate = aaf1.ProjectEndDate)) THEN 
								@journalStartDate
		
							WHEN sd1.EffectiveDate <= @journalStartDate 
								 AND sd1.ExpirationDate >= aaf1.BudgetEndDate  THEN @journalStartDate
								
							WHEN sd1.EffectiveDate >= @journalStartDate
								 AND sd1.EffectiveDate <= aaf1.BudgetEndDate
								 AND (sd1.ExpirationDate <= aaf1.BudgetEndDate 
										or (aaf1.BudgetEndDate = aaf1.ProjectEndDate)) THEN 
								sd1.EffectiveDate
								
	 							WHEN sd1.EffectiveDate >= @journalStartDate
	 								 AND sd1.EffectiveDate <= aaf1.BudgetEndDate
	 								 AND sd1.ExpirationDate >= aaf1.BudgetEndDate THEN
								sd1.EffectiveDate
						END
				END AS 'StartDate'
				,CASE
					-- Handle projects that are not approved that end before fye
					WHEN aaf1.BudgetEndDate < @journalStartDate
						AND aaf1.ProjectEndDate >= @journalStartDate
						AND @fiscalYearEndDate > aaf1.ProjectEndDate THEN
		
						CASE
							WHEN sd1.EffectiveDate <= @journalStartDate 
								 AND sd1.ExpirationDate >= @journalStartDate 
								 AND (sd1.ExpirationDate <= aaf1.ProjectEndDate 
										or (aaf1.BudgetEndDate = aaf1.ProjectEndDate)) THEN 
								case when sd1.ExpirationDate < @fiscalYearEndDate then
												sd1.ExpirationDate Else @fiscalYearEndDate End
		
							WHEN sd1.EffectiveDate <= @journalStartDate 
								 AND sd1.ExpirationDate >= aaf1.ProjectEndDate  THEN  
								aaf1.ProjectEndDate
								
							WHEN sd1.EffectiveDate >= @journalStartDate
								 AND sd1.EffectiveDate <= aaf1.ProjectEndDate
								 AND (sd1.ExpirationDate <= aaf1.ProjectEndDate 
										or (aaf1.BudgetEndDate = aaf1.ProjectEndDate)) THEN 
								case when sd1.ExpirationDate < @fiscalYearEndDate then
												sd1.ExpirationDate Else @fiscalYearEndDate End
								
	 						WHEN sd1.EffectiveDate >= @journalStartDate
	 								 AND sd1.EffectiveDate <= aaf1.ProjectEndDate
	 								 AND sd1.ExpirationDate >= aaf1.ProjectEndDate THEN 
								aaf1.ProjectEndDate
							
						END
		
					-- Handle projects that are not approved that end after fye
					WHEN aaf1.BudgetEndDate < @journalStartDate
						AND aaf1.ProjectEndDate >= @journalStartDate
						AND @fiscalYearEndDate < aaf1.ProjectEndDate THEN
		
						CASE
							WHEN sd1.EffectiveDate <= @journalStartDate 
								 AND sd1.ExpirationDate >=@journalStartDate 
								 AND (sd1.ExpirationDate <= @fiscalYearEndDate 
										or (aaf1.BudgetEndDate = aaf1.ProjectEndDate)) THEN 
								case when sd1.ExpirationDate < @fiscalYearEndDate then
												sd1.ExpirationDate Else @fiscalYearEndDate End
		
							WHEN sd1.EffectiveDate <= @journalStartDate 
								 AND sd1.ExpirationDate >= @fiscalYearEndDate  THEN  
								@fiscalYearEndDate
								
							WHEN sd1.EffectiveDate >= @journalStartDate
								 AND sd1.EffectiveDate <= @fiscalYearEndDate
								 AND (sd1.ExpirationDate <= @fiscalYearEndDate
										or (aaf1.BudgetEndDate = aaf1.ProjectEndDate)) THEN 
								case when sd1.ExpirationDate < @fiscalYearEndDate then
												sd1.ExpirationDate Else @fiscalYearEndDate End
								
	 						WHEN sd1.EffectiveDate >= @journalStartDate
	 								 AND sd1.EffectiveDate <= @fiscalYearEndDate
	 								 AND sd1.ExpirationDate >= @fiscalYearEndDate THEN 
								@fiscalYearEndDate
						END
		
					-- Handle regular projects
					ELSE
		
						CASE
							WHEN sd1.EffectiveDate <= @journalStartDate 
								 AND sd1.ExpirationDate >= @journalStartDate 
								 AND (sd1.ExpirationDate <= aaf1.BudgetEndDate 
										or (aaf1.BudgetEndDate = aaf1.ProjectEndDate)) THEN  
								case when sd1.ExpirationDate < @fiscalYearEndDate then
											case when sd1.ExpirationDate < aaf1.BudgetEndDate  
												or aaf1.BudgetEndDate < @journalStartDate then
													sd1.ExpirationDate
												Else aaf1.BudgetEndDate 
											End
										Else 
											case when @fiscalYearEndDate < aaf1.BudgetEndDate 
														or aaf1.BudgetEndDate < @journalStartDate then
													@fiscalYearEndDate
												Else aaf1.BudgetEndDate 
											End
										End
					
							WHEN sd1.EffectiveDate <= @journalStartDate 
								 AND sd1.ExpirationDate >= aaf1.BudgetEndDate  THEN 
								aaf1.BudgetEndDate
								
							WHEN sd1.EffectiveDate >= @journalStartDate
								 AND sd1.EffectiveDate <= aaf1.BudgetEndDate
								 AND (sd1.ExpirationDate <= aaf1.BudgetEndDate 
										or (aaf1.BudgetEndDate = aaf1.ProjectEndDate)) THEN 
								case when sd1.ExpirationDate < @fiscalYearEndDate then
											case when sd1.ExpirationDate < aaf1.BudgetEndDate  
												or aaf1.BudgetEndDate < @journalStartDate then
													sd1.ExpirationDate
												Else aaf1.BudgetEndDate 
											End
										Else 
											case when @fiscalYearEndDate < aaf1.BudgetEndDate 
														or aaf1.BudgetEndDate < @journalStartDate then
													@fiscalYearEndDate
												Else aaf1.BudgetEndDate 
											End
										End
								
							WHEN sd1.EffectiveDate >= @journalStartDate
	 								 AND sd1.EffectiveDate <= aaf1.BudgetEndDate
	 								 AND sd1.ExpirationDate >= aaf1.BudgetEndDate THEN
								aaf1.BudgetEndDate
						END
		
				END AS 'EndDate'
			FROM 
				PerSalaryDistribution_src sd1 (nolock)
			INNER JOIN 
				AgrAgreement_Fct aaf1 (nolock) 
			ON
				aaf1.FundId = sd1.AgrFundId
			) Effective
			ON
				Effective.[ID] = sd.[ID]
			WHERE
				sd.AnnualRate > 0 
			AND
			(
				(jt.PerPayTypeID <> @salaryPayType OR jt.PerPayFrequencyTypeID <> @monthlyPayFrequencyType OR hrd.PerHRManagementTypeID = @hrManagementTypeNonManaged) 
				AND ejm.IsTracked = @isTracked
			)
			AND
				(@firstName IS NULL OR ap.FirstName LIKE @firstName + '%')
			AND
				(@lastName IS NULL OR ap.LastName LIKE @lastName + '%')
			AND 
				(effective.Days IS NOT NULL AND effective.Days > 0)
			AND
				(@employeeID IS NULL OR ip.EmployeeNumber like @employeeID + '%')
			AND
				(@payDateFrom IS NULL OR sts.PayDate >= @payDateFrom) 
			AND 
				(@payDateTo IS NULL OR sts.PayDate <= @payDateTo)
			AND
				aaf.ProjectEndDate <= @projectEndingDate
			-- Removes duplicate agreements due to multiple funds on the agreement. 
			AND aaf.[Id] = (SELECT MAX(aaf1.[ID]) FROM agragreement_fct aaf1 (nolock) 
							WHERE aaf1.resourceId =aaf.resourceId and aaf1.FundNumber = aaf.FundNumber)
			GROUP BY		
				  ap.LastName
				, ap .FirstName
				, aaf.FundNumber
				, frs.FringeRate
				, AnnualRate
				, Effective.StartDate
				, Effective.EndDate
				, Effective.Days
				, sd.PerEmployeeJobMapId
				, PercentEffort
				, PercentageEffort

		UNION ALL
			-- Retrieve Salary Overview Info for Managed Employees
			SELECT	
				ap.LastName,
				ap.FirstName,
				aaf.FundNumber,
				sd.AnnualRate,
				Effective.StartDate,
				Effective.EndDate,
				sd.PerEmployeeJobMapId,
				sd.AnnualRate/12 AS 'MonthlyRate',
				CONVERT(DECIMAL(12,7), Effective.Days) * 12/@fiscalYearDays AS 'MonthsRemaining',
				(sd.AnnualRate/12 * (CONVERT(DECIMAL(12,7), CONVERT(DECIMAL(12,7), Effective.Days)*12/@fiscalYearDays))) AS 'CommittedSalary',
				ISNULL(frs.FringeRate,0) AS 'FringeRate',
				(sd.AnnualRate/12 * (CONVERT(DECIMAL(12,7),CONVERT(DECIMAL(12,7), Effective.Days)*12/@fiscalYearDays)*(frs.FringeRate))) AS 'CommittedFringe',
				(sd.AnnualRate/12 * (CONVERT(DECIMAL(12,7),CONVERT(DECIMAL(12,7), Effective.Days)*12/@fiscalYearDays)) + 
				(sd.AnnualRate/12 * (CONVERT(DECIMAL(12,7),CONVERT(DECIMAL(12,7), Effective.Days)*12/@fiscalYearDays))*(frs.FringeRate))) AS 'TotalCommitted',
				SUM(ISNULL(ExpenseAmount,0)) AS 'PaidToDate',
				ISNULL(sd.PercentEffort, 0) AS 'TrackedEffort'	
				,ISNULL(aspey.PercentageEffort, 0) AS 'SponsorEffort'		
			FROM			
				PerSalaryDistribution sd (nolock)
			INNER JOIN
				#TempFundCollection f
			ON
				sd.AgrFundId = f.FundID	
			INNER JOIN
				AgrAgreement_Fct aaf (nolock)
			ON
				f.FundID = aaf.FundID
			INNER JOIN		
				PerEmployee_Job_Map ejm (nolock)
			ON
				ejm.[ID] = sd.PerEmployeeJobMapId
			INNER JOIN
				PerHRDepartment hrd (nolock)
			ON
				ejm.PerHRDepartmentID = hrd.ID
			INNER JOIN		
				AdmInternalPerson ip (nolock)
			ON	
				ip.[ID] = ejm.AdmInternalPersonId
		INNER JOIN		
			AdmPerson ap (nolock) 
		ON	
			ap.[ID] = ip.AdmPersonId
		LEFT OUTER JOIN
			PerSalaryTransaction_src sts (nolock)
		ON
			f.FundID = sts.FundID
		AND
			ip.ID = sts.AdmInternalPersonID
		AND
			sts.PayDate <= GETDATE()
		INNER JOIN		
			PerJobType jt (nolock)
		ON	
			jt.[ID] = ejm.PerJobTypeId
		LEFT OUTER JOIN
			PerPayCompany pco (nolock)
		ON
			pco.[Name] = jt.PayCompany
		LEFT OUTER JOIN
			FinAccount_FringeRateStep_Map frsm (nolock)
		ON 	
			frsm.FinaccountId = jt.SalaryAccountId
		AND
			frsm.fwkDomainOrganizationID = ISNULL(pco.InstitutionID, 0) -- Default to MGH if Org is Partners
		-- NOTE: When fringe Rates for Partners are added, the default Institution needs to be removed
		AND frsm.FinFiscalYearId  = (Select MAX(frsm1.FinFiscalYearId) 
									 from FinAccount_FringeRateStep_Map frsm1 (nolock)
									 inner join FinFiscalYear fy1 (nolock) on frsm1.FinFiscalYearId = fy1.[ID]
									 where frsm1.FinaccountId = frsm.FinaccountId
										and frsm1.fwkDomainOrganizationID = frsm.fwkDomainOrganizationID
										and fy1.[Year] <= @fiscalYear)
		LEFT OUTER JOIN
			FinFringeRateStep frs (nolock)
		ON	
			frs.[ID] = frsm.FinFringeRateStepId
		
		LEFT OUTER JOIN  
			SvcEntity_AdmStaffedPerson_Map seaspm (nolock)
		ON
			ap.[ID] = seaspm.AdmPersonId
		AND
			aaf.SvcEntityID = seaspm.SvcEntityID

		LEFT OUTER JOIN	
			AgrStaffedPersonEffortYear aspey (nolock)
		ON				
			seaspm.[ID] = aspey.SvcEntityStaffedPersonMapId
		AND
			aspey.SequenceYear = aaf.budgetYear
		AND
			 aspey.AgrBudgetViewTypeId  = @budgetViewTypeID
		-- remove duplicates staff person year rows.
		AND aspey.[Id] = (SELECT MAX(aspey1.[Id]) FROM AgrStaffedPersonEffortYear aspey1 (nolock)
			WHERE 	seaspm.[Id] = aspey1.SvcEntityStaffedPersonMapId 
			AND aspey1.SequenceYear = aaf.budgetYear
			AND  aspey1.AgrBudgetViewTypeId =@budgetViewTypeID )
			
		INNER JOIN
			(SELECT 
				aaf1.FundId
				,sd1.[ID]
				,CASE
					-- Handle projects that are not approved that end before fye
					WHEN aaf1.BudgetEndDate < @journalStartDate
						AND aaf1.ProjectEndDate >= @journalStartDate
						AND @fiscalYearEndDate > aaf1.ProjectEndDate THEN
						CASE
							WHEN sd1.EffectiveDate <= @journalStartDate 
								 AND sd1.ExpirationDate >= @journalStartDate 
								 AND (sd1.ExpirationDate <= aaf1.ProjectEndDate 
									or (aaf1.BudgetEndDate = aaf1.ProjectEndDate)) THEN 
								datediff(dd, @journalStartDate
										, case when sd1.ExpirationDate < @fiscalYearEndDate then
												sd1.ExpirationDate Else @fiscalYearEndDate End) + 1
					
							WHEN sd1.EffectiveDate <= @journalStartDate 
								 AND sd1.ExpirationDate >= aaf1.ProjectEndDate  THEN 
								datediff(dd, @journalStartDate, aaf1.ProjectEndDate)+1
								
							WHEN sd1.EffectiveDate >= @journalStartDate
								 AND sd1.EffectiveDate <= aaf1.ProjectEndDate
								 AND (sd1.ExpirationDate <= aaf1.ProjectEndDate 
										or (aaf1.BudgetEndDate = aaf1.ProjectEndDate)) THEN 
								datediff(dd, sd1.EffectiveDate
										, case when sd1.ExpirationDate < @fiscalYearEndDate then
												sd1.ExpirationDate Else @fiscalYearEndDate End) + 1
								
 							WHEN sd1.EffectiveDate >= @journalStartDate
 								 AND sd1.EffectiveDate <= aaf1.ProjectEndDate
 								 AND sd1.ExpirationDate >= aaf1.ProjectEndDate THEN 
							datediff(dd, sd1.EffectiveDate, aaf1.ProjectEndDate) + 1

						END
		
					-- Handle projects that are not approved that end after fye
					WHEN aaf1.BudgetEndDate < @journalStartDate
						AND aaf1.ProjectEndDate >= @journalStartDate
						AND @fiscalYearEndDate < aaf1.ProjectEndDate THEN
		
						CASE
							WHEN sd1.EffectiveDate <= @journalStartDate 
								 AND sd1.ExpirationDate >= @journalStartDate 
								 AND (sd1.ExpirationDate <= @fiscalYearEndDate 
										or (aaf1.BudgetEndDate = aaf1.ProjectEndDate)) THEN 
								datediff(dd,@journalStartDate
										, case when sd1.ExpirationDate < @fiscalYearEndDate then
												sd1.ExpirationDate Else @fiscalYearEndDate End) + 1
					
							WHEN sd1.EffectiveDate <= @journalStartDate 
								 AND sd1.ExpirationDate >= @fiscalYearEndDate  THEN 
								datediff(dd,@journalStartDate, @fiscalYearEndDate) + 1
								
							WHEN sd1.EffectiveDate >= @journalStartDate
								 AND sd1.EffectiveDate <= @fiscalYearEndDate
								 AND (sd1.ExpirationDate <= @fiscalYearEndDate 
										or (aaf1.BudgetEndDate = aaf1.ProjectEndDate)) THEN 
								datediff(dd, sd1.EffectiveDate
										, case when sd1.ExpirationDate < @fiscalYearEndDate then
												sd1.ExpirationDate Else @fiscalYearEndDate End) + 1
								
	 						WHEN sd1.EffectiveDate >= @journalStartDate
	 								 AND sd1.EffectiveDate <= @fiscalYearEndDate
	 								 AND sd1.ExpirationDate >= @fiscalYearEndDate THEN 
								datediff(dd, sd1.EffectiveDate, @fiscalYearEndDate) + 1
						END
		
					-- Handle regular projects
					ELSE
						CASE
		
							WHEN sd1.EffectiveDate <= @journalStartDate 
								 AND sd1.ExpirationDate >= @journalStartDate 
								 AND (sd1.ExpirationDate <= aaf1.BudgetEndDate 
										or (aaf1.BudgetEndDate = aaf1.ProjectEndDate)) THEN 
								datediff(dd, @journalStartDate
										, case when sd1.ExpirationDate < @fiscalYearEndDate then
											case when sd1.ExpirationDate < aaf1.BudgetEndDate  
												or aaf1.BudgetEndDate < @journalStartDate then
													sd1.ExpirationDate
												Else aaf1.BudgetEndDate 
											End
										Else 
											case when @fiscalYearEndDate < aaf1.BudgetEndDate 
														or aaf1.BudgetEndDate < @journalStartDate then
													@fiscalYearEndDate
												Else aaf1.BudgetEndDate 
											End
										End) + 1
					
							WHEN sd1.EffectiveDate <= @journalStartDate 
								 AND sd1.ExpirationDate >= aaf1.BudgetEndDate  THEN 
								datediff(dd,@journalStartDate, aaf1.BudgetEndDate) + 1
								
							WHEN sd1.EffectiveDate >= @journalStartDate
								 AND sd1.EffectiveDate <= aaf1.BudgetEndDate
								 AND (sd1.ExpirationDate <= aaf1.BudgetEndDate 
										or (aaf1.BudgetEndDate = aaf1.ProjectEndDate)) THEN 
								datediff(dd, sd1.EffectiveDate
										, case when sd1.ExpirationDate < @fiscalYearEndDate then
											case when sd1.ExpirationDate < aaf1.BudgetEndDate  
												or aaf1.BudgetEndDate < @journalStartDate then
													sd1.ExpirationDate
												Else aaf1.BudgetEndDate 
											End
										Else 
											case when @fiscalYearEndDate < aaf1.BudgetEndDate 
														or aaf1.BudgetEndDate < @journalStartDate then
													@fiscalYearEndDate
												Else aaf1.BudgetEndDate 
											End
										End) + 1
								
	 						WHEN sd1.EffectiveDate >= @journalStartDate
	 								 AND sd1.EffectiveDate <= aaf1.BudgetEndDate
	 								 AND sd1.ExpirationDate >= aaf1.BudgetEndDate THEN 
									datediff(dd, sd1.EffectiveDate, aaf1.BudgetEndDate) + 1
						END
				END AS 'Days'
				,CASE
					-- Handle projects that are not approved that end before fye
					WHEN aaf1.BudgetEndDate < @journalStartDate
						AND aaf1.ProjectEndDate >= @journalStartDate
						AND @fiscalYearEndDate > aaf1.ProjectEndDate THEN
		
						CASE
							WHEN sd1.EffectiveDate <= @journalStartDate 
								 AND sd1.ExpirationDate >= @journalStartDate 
								 AND (sd1.ExpirationDate <= aaf1.ProjectEndDate 
										or (aaf1.BudgetEndDate = aaf1.ProjectEndDate)) THEN 
									@journalStartDate
		
							WHEN sd1.EffectiveDate <= @journalStartDate 
								 AND sd1.ExpirationDate >= aaf1.ProjectEndDate  THEN @journalStartDate
								
							WHEN sd1.EffectiveDate >= @journalStartDate
								 AND sd1.EffectiveDate <= aaf1.ProjectEndDate
								 AND (sd1.ExpirationDate <= aaf1.ProjectEndDate 
										or (aaf1.BudgetEndDate = aaf1.ProjectEndDate)) THEN 
									sd1.EffectiveDate
								
	 						WHEN sd1.EffectiveDate >= @journalStartDate
	 								 AND sd1.EffectiveDate <= aaf1.ProjectEndDate
	 								 AND sd1.ExpirationDate >= aaf1.ProjectEndDate THEN 
								sd1.EffectiveDate
						END
		
					-- Handle projects that are not approved that end after fye
					WHEN aaf1.BudgetEndDate < @journalStartDate
						AND aaf1.ProjectEndDate >= @journalStartDate
						AND @fiscalYearEndDate < aaf1.ProjectEndDate THEN
		
						CASE
							WHEN sd1.EffectiveDate <= @journalStartDate 
								 AND sd1.ExpirationDate >= @journalStartDate 
								 AND (sd1.ExpirationDate <= @fiscalYearEndDate 
										or (aaf1.BudgetEndDate = aaf1.ProjectEndDate)) THEN 
								@journalStartDate
		
							WHEN sd1.EffectiveDate <= @journalStartDate 
								 AND sd1.ExpirationDate >= @fiscalYearEndDate  THEN @journalStartDate
								
							WHEN sd1.EffectiveDate >= @journalStartDate
								 AND sd1.EffectiveDate <= @fiscalYearEndDate
								 AND (sd1.ExpirationDate <= @fiscalYearEndDate
										or (aaf1.BudgetEndDate = aaf1.ProjectEndDate)) THEN 
								sd1.EffectiveDate
								
	 						WHEN sd1.EffectiveDate >= @journalStartDate
	 								 AND sd1.EffectiveDate <= @fiscalYearEndDate
	 								 AND sd1.ExpirationDate >= @fiscalYearEndDate THEN 
								sd1.EffectiveDate
						END
		
					-- Handle regular projects
					ELSE
		
						CASE
							WHEN sd1.EffectiveDate <= @journalStartDate 
								 AND sd1.ExpirationDate >= @journalStartDate 
								 AND (sd1.ExpirationDate <= aaf1.BudgetEndDate 
										or (aaf1.BudgetEndDate = aaf1.ProjectEndDate)) THEN 
								@journalStartDate
		
							WHEN sd1.EffectiveDate <= @journalStartDate 
								 AND sd1.ExpirationDate >= aaf1.BudgetEndDate  THEN @journalStartDate
								
							WHEN sd1.EffectiveDate >= @journalStartDate
								 AND sd1.EffectiveDate <= aaf1.BudgetEndDate
								 AND (sd1.ExpirationDate <= aaf1.BudgetEndDate 
										or (aaf1.BudgetEndDate = aaf1.ProjectEndDate)) THEN 
								sd1.EffectiveDate
								
	 							WHEN sd1.EffectiveDate >= @journalStartDate
	 								 AND sd1.EffectiveDate <= aaf1.BudgetEndDate
	 								 AND sd1.ExpirationDate >= aaf1.BudgetEndDate THEN
								sd1.EffectiveDate
						END
				END AS 'StartDate'
				,CASE
					-- Handle projects that are not approved that end before fye
					WHEN aaf1.BudgetEndDate < @journalStartDate
						AND aaf1.ProjectEndDate >= @journalStartDate
						AND @fiscalYearEndDate > aaf1.ProjectEndDate THEN
		
						CASE
							WHEN sd1.EffectiveDate <= @journalStartDate 
								 AND sd1.ExpirationDate >= @journalStartDate 
								 AND (sd1.ExpirationDate <= aaf1.ProjectEndDate 
										or (aaf1.BudgetEndDate = aaf1.ProjectEndDate)) THEN 
								case when sd1.ExpirationDate < @fiscalYearEndDate then
										sd1.ExpirationDate Else @fiscalYearEndDate End
		
							WHEN sd1.EffectiveDate <= @journalStartDate 
								 AND sd1.ExpirationDate >= aaf1.ProjectEndDate  THEN  
								aaf1.ProjectEndDate
								
							WHEN sd1.EffectiveDate >= @journalStartDate
								 AND sd1.EffectiveDate <= aaf1.ProjectEndDate
								 AND (sd1.ExpirationDate <= aaf1.ProjectEndDate 
										or (aaf1.BudgetEndDate = aaf1.ProjectEndDate)) THEN 
								case when sd1.ExpirationDate < @fiscalYearEndDate then
										sd1.ExpirationDate Else @fiscalYearEndDate End
								
	 						WHEN sd1.EffectiveDate >= @journalStartDate
	 								 AND sd1.EffectiveDate <= aaf1.ProjectEndDate
	 								 AND sd1.ExpirationDate >= aaf1.ProjectEndDate THEN 
								aaf1.ProjectEndDate
							
						END
		
					-- Handle projects that are not approved that end after fye
					WHEN aaf1.BudgetEndDate < @journalStartDate
						AND aaf1.ProjectEndDate >= @journalStartDate
						AND @fiscalYearEndDate < aaf1.ProjectEndDate THEN
		
						CASE
							WHEN sd1.EffectiveDate <= @journalStartDate 
								 AND sd1.ExpirationDate >=@journalStartDate 
								 AND (sd1.ExpirationDate <= @fiscalYearEndDate 
										or (aaf1.BudgetEndDate = aaf1.ProjectEndDate)) THEN 
								case when sd1.ExpirationDate < @fiscalYearEndDate then
										sd1.ExpirationDate Else @fiscalYearEndDate End
		
							WHEN sd1.EffectiveDate <= @journalStartDate 
								 AND sd1.ExpirationDate >= @fiscalYearEndDate  THEN  
								@fiscalYearEndDate
								
							WHEN sd1.EffectiveDate >= @journalStartDate
								 AND sd1.EffectiveDate <= @fiscalYearEndDate
								 AND (sd1.ExpirationDate <= @fiscalYearEndDate
										or (aaf1.BudgetEndDate = aaf1.ProjectEndDate)) THEN 
								case when sd1.ExpirationDate < @fiscalYearEndDate then
										sd1.ExpirationDate Else @fiscalYearEndDate End
								
	 						WHEN sd1.EffectiveDate >= @journalStartDate
	 								 AND sd1.EffectiveDate <= @fiscalYearEndDate
	 								 AND sd1.ExpirationDate >= @fiscalYearEndDate THEN 
								@fiscalYearEndDate
						END
		
					-- Handle regular projects
					ELSE
		
						CASE
							WHEN sd1.EffectiveDate <= @journalStartDate 
								 AND sd1.ExpirationDate >= @journalStartDate 
								 AND (sd1.ExpirationDate <= aaf1.BudgetEndDate 
										or (aaf1.BudgetEndDate = aaf1.ProjectEndDate)) THEN  
								case 
									when sd1.ExpirationDate < @fiscalYearEndDate then
										case when sd1.ExpirationDate < aaf1.BudgetEndDate  
											or aaf1.BudgetEndDate < @journalStartDate then
												sd1.ExpirationDate
											Else aaf1.BudgetEndDate 
										End
									Else 
										case when @fiscalYearEndDate < aaf1.BudgetEndDate 
													or aaf1.BudgetEndDate < @journalStartDate then
												@fiscalYearEndDate
											Else aaf1.BudgetEndDate 
										End
								End

					
							WHEN sd1.EffectiveDate <= @journalStartDate 
								 AND sd1.ExpirationDate >= aaf1.BudgetEndDate  THEN 
								aaf1.BudgetEndDate
								
							WHEN sd1.EffectiveDate >= @journalStartDate
								 AND sd1.EffectiveDate <= aaf1.BudgetEndDate
								 AND (sd1.ExpirationDate <= aaf1.BudgetEndDate 
										or (aaf1.BudgetEndDate = aaf1.ProjectEndDate)) THEN 
								case 
									when sd1.ExpirationDate < @fiscalYearEndDate then
										case when sd1.ExpirationDate < aaf1.BudgetEndDate  
											or aaf1.BudgetEndDate < @journalStartDate then
												sd1.ExpirationDate
											Else aaf1.BudgetEndDate 
										End
									Else 
										case when @fiscalYearEndDate < aaf1.BudgetEndDate 
													or aaf1.BudgetEndDate < @journalStartDate then
												@fiscalYearEndDate
											Else aaf1.BudgetEndDate 
										End
								End
								
							WHEN sd1.EffectiveDate >= @journalStartDate
	 								 AND sd1.EffectiveDate <= aaf1.BudgetEndDate
	 								 AND sd1.ExpirationDate >= aaf1.BudgetEndDate THEN
								aaf1.BudgetEndDate
						END
		
				END AS 'EndDate'
			FROM 
				PerSalaryDistribution sd1 (nolock)
			INNER JOIN 
				AgrAgreement_Fct aaf1 (nolock) 
			ON
				aaf1.FundId = sd1.AgrFundId
			) Effective
			ON
				Effective.[ID] = sd.[ID]
			WHERE
				sd.AnnualRate > 0 
			AND
				ejm.IsTracked = @isTracked
			AND
				(@firstName IS NULL OR ap.FirstName LIKE @firstName + '%')
			AND
				(@lastName IS NULL OR ap.LastName LIKE @lastName + '%')
			AND 
				(effective.Days IS NOT NULL AND effective.Days > 0)
			AND
				(@employeeID IS NULL OR ip.EmployeeNumber like @employeeID + '%')
			AND
				(@payDateFrom IS NULL OR sts.PayDate >= @payDateFrom) 
			AND 
				(@payDateTo IS NULL OR sts.PayDate <= @payDateTo)
			AND
				aaf.ProjectEndDate <= @projectEndingDate
			
			
			-- Removes duplicate agreements due to multiple funds on the agreement. 
			AND aaf.[Id] = (SELECT MAX(aaf1.[ID]) FROM agragreement_fct aaf1 (nolock) 
							WHERE aaf1.resourceId =aaf.resourceId and aaf1.FundNumber = aaf.FundNumber)
			GROUP BY		
				  ap.LastName
				, ap .FirstName
				, aaf.FundNumber
				, frs.FringeRate
				, AnnualRate
				, Effective.StartDate
				, Effective.EndDate
				, Effective.Days
				, sd.PerEmployeeJobMapId
				, PercentEffort
				, PercentageEffort
				
			ORDER BY 
				 lastname
				,firstname
				,fundnumber
	End

	IF OBJECT_ID(N'tempdb..#TempFundCollection', N'U') IS NOT NULL 	drop table #TempFundCollection
	
	SET NOCOUNT OFF
END








GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Altering [dbo].[GetAgreementSummary]'
GO

/******************************************************************
* Name:			GetAgreementSummary
* Purpose:		Retrieves an agreement
*
* PARAMETERS
* Name					Description					
* -------------			-------------------------------------------
* @agreementId			Agreement Id.	(REQUIRED)
* @fundNumber			Grant number	(not required)
*
******************************************************************/
ALTER Procedure [dbo].[GetAgreementSummary]
(
	@agreementId	INTEGER,
	@fundNumber		VARCHAR(30) = NULL
)
AS
BEGIN

	SET NOCOUNT ON

	IF (ltrim(rtrim(@fundNumber)) = '') OR (@fundNumber = '&nbsp;')
		SET @fundNumber = NULL

	-- Retrieve agreement informations
	select
		agf.AgreementID,
		agf.ResourceID,
		aty.Name as AgreementType,
		isnull(agf.PSActivityDescription, '') as ActivityType,
		st.Name as StatusType,
		isnull(agf.FundNumber, '') as FundNumber,
		case datalength(agf.Title)
			when 1 then 'No Title'	-- The datalength of a text field is 1 when it is empty!
			else agf.Title
		end as Title,
		agf.ProjectStartDate, 
		agf.ProjectEndDate, 
		isnull(agf.BudgetStartDate, '') as BudgetStartDate,
		isnull(agf.BudgetEndDate, '') as BudgetEndDate,
		isnull(agf.SponsorName, '') as SponsorName,
		isnull(sgt.Name, '') as SponsorGroupType,
		LTRIM(RTRIM(isnull(ra1.FirstName, '') + ' ' + isnull(ra1.LastName, ''))) as AdminNamePreAward,
		isnull(ra1.Phone, '') as AdminNumberPreAward,
		LTRIM(RTRIM(isnull(ra2.FirstName, '') + ' ' + isnull(ra2.LastName, ''))) as AdminNamePostAward,
		isnull(ra2.Phone, '') as AdminNumberPostAward,
		isnull(foc.PSCode, '') as FundCode,
		isnull(agf.PIFirstName, '') + ' ' + isnull(agf.PILastName, '') as PIName, 
		isnull(SponType.Name, '') as SponsorTypeName
	from 
		AgrAgreement_Fct agf 
	inner join AgrAgreementType aty on agf.AgrAgreementTypeId = aty.[Id]
	inner join AgrAgreementStatusType st on st.[Id] = agf.StatusTypeId
	left outer join AdmSponsorGroupType sgt on sgt.[Id] = agf.SponsorGroupTypeId
	left outer join FwkDomainOrganization do on do.[Id] = agf.OrganizationId
	left outer join AdmResearchAdministrators ra1 on ra1.[Id] = do.PreAwardResearchAdminId
	left outer join AdmResearchAdministrators ra2 on ra2.[Id] = do.PostAwardResearchAdminId
	left outer join AgrFund af on agf.FundId = af.[Id]
	left outer join AgrFundOverheadClassification foc on af.AgrFundOverheadClassificationId = foc.[Id]
	left outer join AdmSponsorType sponType on sponType.Id = agf.SponsorTypeId 
	where agf.AgreementId = @agreementId
	and (@fundNumber IS NULL or agf.FundNumber = @fundNumber)

	SET NOCOUNT OFF
END


GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Altering [dbo].[GetStudyStaff]'
GO
SET QUOTED_IDENTIFIER OFF
GO

/************************************************************************************************
* Name:		GetStudyStaff                                                            
* Purpose:	Stored procedure for retrieving the set of people staffed to a study 

* PARAMETERS  
*	Name			Description
* -------------------------	-----------------------------
* @protocolId			Id of the protocol to retrieve study staff for (not used if 
					@protocolProcessId is supplied)
* @protocolProcessId		Id of the protocolProcess to retrieve study staff for	 		
************************************************************************************************/
ALTER procedure dbo.GetStudyStaff
(
	@protocolId int,
	@protocolProcessId int = 0
)
as

begin

set nocount on

	-- get ProtocolNumber and FwkResourceId of Protocol
	declare @protocolNumber varchar(25)
	declare @resourceId int
	
	-- if @protocolId = 0, a processId MUST be provided
	if (@protocolId = 0)
	begin
		if (@protocolProcessId = 0)
			begin
				raiserror('Either @protocolId or @protocolProcessId must be non-zero', 16, 1)
				return
			end
		select @protocolId = ProtocolId
		from ProtocolProcess where [Id] = @protocolProcessId

	end

	select @protocolNumber = ProtocolNumber, @resourceId = FwkResourceId
	from Protocol where [Id] = @protocolId

	declare @protocolStaff table (protocolId int, protocolNumber varchar(36),
		[id] int, iscurrent bit, admpersonid int, role varchar(50), accessbitvalue int,
		contactPerson bit, organizationId int, organizationName varchar(250),
		lastName varchar(64), RexName varchar(50), roleId int, addedProtocolProcessId int,
		removedProtocolProcessId int,
		institutionalName varchar(256), documentId int, processName varchar(12),
		processType varchar(256), userId int)
	
	insert into @protocolStaff 
		(protocolId, protocolNumber,
		[id], iscurrent, admpersonid, [role], accessbitvalue,
		contactPerson, organizationId, organizationName,
		lastName, RexName, roleId, addedProtocolProcessId, removedProtocolProcessId, 
		institutionalName, documentId, processName,
		processType, userId)
		select distinct
			@protocolId as 'ProtocolId',
			@protocolNumber as 'ProtocolNumber',	
			map.[Id] as 'Id',
			map.IsCurrent,
			ap.[Id] as 'AdmPersonId',
			type.[Name] as 'Role',
			-- fake out access level for external people (no access for them since no login)
			-- make it look like they have the lowest possible (read)
			case when ap.AdmPersonTypeId = 1 then IsNull(access.AccessRightBitmask, 0)
				else 0
			end as 'AccessBitValue',
 			case
				   when fdcMap.FwkResourceId is null then 0 
				   else 1
	    		end as 'ContactPerson',
			map.OrganizationId ,
			IsNull(aep.Institution, fdo.FullyQualifiedName) as 'OrganizationName',
			ap.LastName,	-- to enable using for the ordering
			type.RexName,	-- to enable using for the ordering
			map.ProtocolStaffTypeId as 'RoleId',
			map.AddedProtocolProcessId,
			map.RemovedProtocolProcessId,
			fdo.[Name] as 'InstitutionalName',
			apdMap.DocumentId,
			pp.[Name] as 'ProcessName',	
			pp.Type as 'ProcessType',	
			ap.FwkDomainUserId as 'UserId'

			from ProtocolStaff_Map map
			left join Protocol p
			on map.ProtocolNumber = p.ProtocolNumber
			left join Protocol p2
			on map.ProtocolId = p.[Id]
			left join ProtocolStaffingType type
			on map.ProtocolStaffTypeId = type.[Id]
			inner join AdmPerson ap
			on map.AdmPersonId = ap.[Id]
			left join FwkDomainUser fdu
			on ap.FwkDomainUserId = fdu.[Id]
			left join FwkResource_DomainUser_Map access
			on fdu.[Id] = access.FwkDomainUserId		
			and p.FwkResourceId = access.FwkResourceId
			left join FwkResource_AdmPerson_Contact_Map fdcMap
			on fdcMap.AdmPersonId = ap.[Id] 
			and fdcMap.FwkResourceId = p.FwkResourceId
			left join FwkDomainOrganization fdo
			on map.OrganizationId = fdo.[Id]
			left join AdmExternalPerson aep
			on aep.AdmPersonId = ap.[Id]
			left join AdmPerson_Protocol_Document_Map apdMap
			on (apdMap.AdmPersonId = ap.[Id] and apdMap.ProtocolId = @protocolId)
			left join ProtocolProcess pp
			on (map.AddedProtocolProcessId = pp.[Id])
		
			where (map.IsCurrent = 1 and 
				((isnull(map.ProtocolNumber, '') = isnull(@protocolNumber, 'a')) 
				 or (isnull(map.ProtocolId, -1) = case when @protocolId = 0 then -2
									else @protocolId
								end)))
			and p.IsCurrent = 1
			and (isnull(map.RemovedProtocolProcessID, -1) <> @protocolProcessId)

			order by ap.LastName
----------------------------------------------------------------
	if (@protocolProcessId <> 0)
		
		select distinct
		@protocolId as 'ProtocolId',
		@protocolNumber as 'ProtocolNumber',	
		map.[Id] as 'Id',
		map.IsCurrent,
		ap.[Id] as 'AdmPersonId',
		type.[Name] as 'Role',
		-- fake out access level for external people (no access for them since no login)
		-- make it look like they have the lowest possible (read)
		case when ap.AdmPersonTypeId = 1 then IsNull(access.AccessRightBitmask, 0)
			else 0
		end as 'AccessBitValue',
 		case
	           when fdcMap.FwkResourceId is null then 0 
	           else 1
	    	end as 'ContactPerson',
		map.OrganizationId,
		-- if the person is not external, aep.Institution will be null
		IsNull(aep.Institution, fdo.FullyQualifiedName) as 'OrganizationName',
		ap.LastName,	-- to enable using for the ordering
		type.RexName,	-- to enable using for the ordering
		map.ProtocolStaffTypeId as 'RoleId',
		map.AddedProtocolProcessId,
		map.RemovedProtocolProcessId,
		fdo.[Name] as 'InstitutionalName',
		apdMap.DocumentId,
		pp.[Name] as 'ProcessName',
		pp.Type as 'ProcessType',
		ap.FwkDomainUserId as 'UserId'

		from ProtocolStaff_Map map
		inner join ProtocolProcess pp
		on map.AddedProtocolProcessID = pp.[Id]
		inner join Protocol p
		on isnull(pp.ProtocolId, map.ProtocolId) = p.[Id]
		left join ProtocolStaffingType type
		on map.ProtocolStaffTypeId = type.[Id]
		inner join AdmPerson ap
		on map.AdmPersonId = ap.[Id]
		left join FwkDomainUser fdu
		on ap.FwkDomainUserId = fdu.[Id]
		left join FwkResource_DomainUser_Map access
		on fdu.[Id] = access.FwkDomainUserId
		and access.FwkResourceId = p.FwkResourceId
		left join FwkResource_AdmPerson_Contact_Map fdcMap
		on fdcMap.AdmPersonId = ap.[Id] 
		and fdcMap.FwkResourceId = p.FwkResourceId
		left join FwkDomainOrganization fdo
		on map.OrganizationId = fdo.[Id]
		left join AdmExternalPerson aep
		on aep.AdmPersonId = ap.[Id]
		left join AdmPerson_Protocol_Document_Map apdMap
		on (apdMap.AdmPersonId = ap.[Id] and apdMap.ProtocolId = @protocolId)
	
		where ((isnull(map.AddedProtocolProcessID, 0) = @protocolProcessId) and 
			(isnull(map.RemovedProtocolProcessID, 0) <> @protocolProcessId))

		union 
		select * from @protocolStaff
		order by ap.LastName

	else
		select * from @protocolStaff
end


GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Altering [dbo].[DeleteProtocolProcess]'
GO
SET ANSI_NULLS OFF
GO

ALTER PROCEDURE [dbo].[DeleteProtocolProcess]  (  
@id    INTEGER = 0  
)  
  
AS  
  
BEGIN  
 DECLARE @TempQAIds TABLE(  
 [QuestionnaireAnswerId] [int] NOT NULL  
 )  
  
 DECLARE @TempDocIds TABLE(  
 [DocumentId] [int] NOT NULL  
 )  
 
DECLARE @TempExecId TABLE(
[ID] [int],
ExecutionId int,
ProtocolProcessId int
)
  
 DELETE Answer WHERE QuestionnaireAnswerId in (SELECT QuestionnaireAnswerId FROM ProtocolVersion_QuestionnaireAnswer_Map  
     WHERE ProtocolVersionId in( SELECT Id FROM ProtocolVersion WHERE ProtocolProcessId = @id) )  
  
 INSERT INTO @TempQAIds (QuestionnaireAnswerId)  
 SELECT QuestionnaireAnswerId   
 FROM ProtocolVersion_QuestionnaireAnswer_Map  
 WHERE ProtocolVersionId in ( SELECT Id FROM ProtocolVersion WHERE ProtocolProcessId = @id)  
  
 DELETE ProtocolVersion_QuestionnaireAnswer_Map   
 WHERE QuestionnaireAnswerId in (SELECT QuestionnaireAnswerId FROM @TempQAIds)  
  
 DELETE QuestionnaireAnswer WHERE Id in (SELECT QuestionnaireAnswerId FROM @TempQAIds)  
  
 INSERT INTO @TempDocIds (DocumentId)  
 SELECT DocumentId FROM ProtocolDocument WHERE AddedPPId = @id  AND DocumentID IS NOT NULL
   
 DELETE ProtocolDocument WHERE AddedPPId = @id  
  
 DELETE Document WHERE Id in (Select DocumentId from @TempDocIds)  
  
 DELETE ProtocolVersion WHERE ProtocolProcessId = @id  

 --should delete from child table if it is there.
 DELETE asm	
 FROM ProtocolStaff_Map asm 
 INNER JOIN ProtocolProcess pp 
 ON pp.Id= asm.AddedProtocolProcessID
 WHERE pp.Id = @id

 
 -- Set the Removed PP Id to null if there are any for this process
 UPDATE ProtocolStaff_Map Set RemovedProtocolProcessID = NULL where RemovedProtocolProcessID = @id

 --DELETE ProtocolProcess_Workflow_Map where ProtocolProcessId = @id
 DECLARE @workflowExecutionId AS INT
 
 INSERT INTO @TempExecId
 Exec GetWorkflowMapData @id, 0
 
 SET @workflowExecutionId = (SELECT IsNull(ExecutionId, 0) FROM @TempExecId)
 IF (@workflowExecutionId <> 0)
 BEGIN
	--CleanWorkflowItem updates the protocol and the processes status to WIP. The second parameter indicates the sproc NOT to do that.
	EXEC CleanWorkflowItem @workflowExecutionId, 0
 END

BEGIN
 DELETE ProtocolProcess_LogItem_Map where ProtocolProcessId = @id
END

BEGIN
 DELETE LogItem WHERE Id in (Select LogItemId from ProtocolProcess_LogItem_Map WHERE ProtocolProcessId = @id)
END


 DELETE ProtocolProcess WHERE Id = @id  
   
IF @@ERROR <> 0  
 BEGIN  
  RAISERROR('Unable to Delete Protocol Process', 16, 1)  
  RETURN  
END      
    
END  


GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Creating [dbo].[MapStagedStaffedPersonFromInfoEd]'
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
    
CREATE PROCEDURE dbo.MapStagedStaffedPersonFromInfoEd     
    
AS    
BEGIN    
    
 SET NOCOUNT ON;    
    
 -- mark all records as valid by default    
 UPDATE Stg_IE_SvcEntityStaffedPerson_Ctl    
 SET IsValid = 1    
    
 -- first, insert any staff person roles that don't already exist    
 SELECT DISTINCT LTRIM(RTRIM(s.sRole)) AS sRole    
 INTO   #tmp1    
 FROM   Stg_IE_SvcEntityStaffedPerson_Ctl s    
 LEFT OUTER JOIN AdmStaffedPersonType t    
  ON    LTRIM(RTRIM(s.sRole)) = LTRIM(RTRIM(t.[Name]))    
 WHERE   t.[Id] IS NULL    
    
 IF (@@ROWCOUNT > 0)    
 BEGIN    
  INSERT AdmStaffedPersonType    
    (    
     [Name], [Description], RexName, IsSiteResponsible    
    )    
  SELECT sRole, sRole, sRole, 0    
  FROM #tmp1    
 END    
    
 -- temp table is created even if no rows were inserted, so drop it    
 DROP TABLE #tmp1    
    
 -- now, look up some type data    
 UPDATE Stg_IE_SvcEntityStaffedPerson_Ctl    
 SET  AdmStaffedPersonTypeId = AdmStaffedPersonType.[Id]    
 FROM AdmStaffedPersonType    
 WHERE LTRIM(RTRIM(Stg_IE_SvcEntityStaffedPerson_Ctl.sRole)) = LTRIM(RTRIM(AdmStaffedPersonType.[Name]))    
    
 UPDATE Stg_IE_SvcEntityStaffedPerson_Ctl    
 SET  AgrBudgetViewTypeId = AgrBudgetViewType.[Id]    
 FROM AgrBudgetViewType    
 WHERE LTRIM(RTRIM(Stg_IE_SvcEntityStaffedPerson_Ctl.sBudgetView)) = LTRIM(RTRIM(AgrBudgetViewType.[Name]))    
    
 -- look for SvcEntityId    
 UPDATE STG     
 SET STG.SvcEntityId = A.SvcEntityId    
 FROM Stg_IE_SvcEntityStaffedPerson_Ctl STG JOIN AgrAgreement A    
ON STG.prop_no = A.PropNumber    
 and A.Id = (select max(id) from AgrAgreement ag1 where ag1.PropNumber = A.PropNumber)    

    
 -- look for AdmPersonId    
 UPDATE STG     
 SET STG.AdmPersonId = AP.Id    
 FROM Stg_IE_SvcEntityStaffedPerson_Ctl STG JOIN FwkDomainUser DU    
  ON STG.sUserName = DU.Username    
 JOIN AdmPerson AP     
  ON DU.Id = AP.FwkDomainUserId    
  
 -- look for AdmPersonId  on the basis of facultyid  
  
  Update STG   
 set AdmPersonId  = A.AdmPersonId  
    from           
    AdmPerson_InfoEdFaculty_Map A        
    inner join     Stg_IE_SvcEntityStaffedPerson_Ctl STG  
 on A.Unique_ID = STG.sFacultyId  
 where STG.AdmPersonId is NULL  
  
    
 -- mark invalid records    
 UPDATE Stg_IE_SvcEntityStaffedPerson_Ctl    
 SET IsValid = 0    
 WHERE SvcEntityId IS NULL    
 OR  AdmStaffedPersonTypeId IS NULL    
 OR  AgrBudgetViewTypeId IS NULL    
 OR  AdmPersonId IS NULL    
    
 -- find existing records    
 UPDATE Stg_IE_SvcEntityStaffedPerson_Ctl    
 SET SvcEntityStaffedPersonMapId = MAP.Id,    
 IsExist = 1    
 FROM SvcEntity_AdmStaffedPerson_Map MAP    
 WHERE MAP.SvcEntityId = Stg_IE_SvcEntityStaffedPerson_Ctl.SvcEntityId    
 AND MAP.AdmPersonId = Stg_IE_SvcEntityStaffedPerson_Ctl.AdmPersonId    
 AND IsValid = 1    
    
END    
  

GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Altering [dbo].[GetBudgetYears]'
GO

/******************************************************************
* Name:		GetBudgetYears
* Purpose:	Procedure to get the list of Budget Years for the specified Fund Number.
*
* PARAMETERS
* Name				Description
* -------------		-------------------------------------------
* @fundNumber
*
* RETURN VALUE
* Value				Description
* --------------	-------------------------------------------
* N/A				N/A
******************************************************************/
/*GetBudgetYears 152355
DROP PROCEDURE [dbo].[GetBudgetYears]
******************************************************************/
ALTER PROCEDURE [dbo].[GetBudgetYears]
(
	@fundNumber VARCHAR(30)
)
AS
BEGIN
	SET NOCOUNT ON

	SELECT	DISTINCT
					af2.FundNumber,
					YEAR(abf.BudgetStartDate) AS BudgetYear,
					abf.BudgetStartDate AS BudgetStartDate,
					abf.BudgetEndDate AS BudgetEndDate,
					CONVERT(varchar(10),abf.BudgetStartDate,101) + '|' + CONVERT(varchar(10),abf.BudgetEndDate,101) AS BudgetDates
	INTO			#tmp1
	FROM			AgrAgreement_Fct af1
	INNER JOIN		AgrAgreement_Fct af2
		ON				af1.FolderNumber = af2.FolderNumber
	INNER JOIN		AgrBudget_Fct abf
		ON				af2.FundId = abf.FundId
	INNER JOIN		AgrBudgetItem bi
		ON				abf.BudgetItemId = bi.Id
	INNER JOIN		AgrBudget b
		ON				bi.AgrBudgetId = b.Id
	WHERE			af1.FundNumber = @fundNumber
	AND				NOT (abf.BudgetStartDate IS NULL)
	AND				abf.BudgetViewTypeId in (	select BudgetViewTypeId
												from AgrBudget_Fct abf2
													inner join AgrBudgetViewType v on v.Id = abf2.BudgetViewTypeId 
													and V.Name = 'Fully Executed/Awarded' 
												where abf2.FundId = abf.FundId)
	AND				b.IsAdjustment = 0
	ORDER BY		BudgetYear, af2.FundNumber

	IF @@ROWCOUNT = 0
	BEGIN
		-- Get the last GL post date
		DECLARE	@glPostAsOfDate	DATETIME
		CREATE TABLE #RefreshDatesTable (glPostAsOfDate datetime, salaryAsOfDate datetime, poapAsOfDate datetime)
		INSERT INTO #RefreshDatesTable EXEC GetRefreshDates
		SELECT @glPostAsOfDate = glPostAsOfDate FROM #RefreshDatesTable
		DROP TABLE #RefreshDatesTable

		-- insert one row with fiscal year of the last GL post
		INSERT	#tmp1 (FundNumber, BudgetYear, BudgetStartDate, BudgetEndDate, BudgetDates)
		SELECT	@fundNumber,
				YEAR(@glPostAsOfDate) AS BudgetYear,
				@glPostAsOfDate AS BudgetStartDate,
				GetDate() AS BudgetEndDate,
				CONVERT(varchar(10),@glPostAsOfDate,101) + '|' + CONVERT(varchar(10),GetDate(),101) AS BudgetDates
	END

	SELECT		IDENTITY(int,1,1) AS BudgetYearNumber,
				FundNumber,
				BudgetYear,
				BudgetStartDate, 
				BudgetEndDate,
				BudgetDates
	INTO		#tmp2
	FROM		#tmp1
	ORDER BY	BudgetYear, FundNumber

	SELECT		BudgetYear AS 'Years',
				FundNumber,
				'Budget Year ' + CAST(BudgetYearNumber as varchar) + ' - ' + FundNumber AS 'BudgetDescription',
				BudgetDates,
				BudgetStartDate, 
				BudgetEndDate
	FROM		#tmp2
	ORDER BY	BudgetYearNumber DESC

	drop table #tmp1
	drop table #tmp2
END


GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Creating [dbo].[GetCOIUsersForNotification]'
GO
/******************************************************************                
* Name:   ExecuteCOINotification                
* Purpose:  Notify/Remind users to fill out COIs                
*                
* PARAMETERS                
* Name        Description                     
* -------------     -------------------------------------------                
*  @type               Type of notification      
*  @institutionId      Institution under which the users have to be notified   
*  @lastActivityDate   Last activity date(for open enrollment)            
******************************************************************/                
                
CREATE Procedure [dbo].[GetCOIUsersForNotification]       
(                
 @type Varchar(50),              
 @institutionId int = 0,              
 @lastActivityDate Datetime = NUll              
)                
AS                
BEGIN                
                
 SET NOCOUNT ON                
 --Create the temporary table to hold the list of users having having access to COI               
 DECLARE @TempPersonIds TABLE (                
 [RowNum] INT IDENTITY (1,1),                
 [Id] INT                
 )                
 
Insert into @tempPersonIds Exec dbo.ExecuteCOIOpenEnrollment @institutionId,@lastActivityDate,@type
   
DECLARE @TempPersonEmail TABLE (                
 [RowNum] INT IDENTITY (1,1),                
 [EmailAddress] varchar(250),
 [FullName]varchar(300)                
 )     
		Insert into @TempPersonEmail SELECT E.EmailAddress,rtrim(ltrim(adp.LastName))+', '+rtrim(ltrim(adp.FirstName))  as FullName--'LMCANULTY@PARTNERS.ORG'as EmailAddress                 
		  FROM AdmEmailAddress E 
			INNER JOIN AdmEmailAddressType ET 
				ON E.AdmEmailAddressTypeId = ET.Id
		  	INNER JOIN AdmPerson adp 
				ON adp.Id = e.admPersonId	                 
		  WHERE ET.Name = 'Primary'                
		  AND E.EmailAddress IS NOT NULL                
		  AND E.EmailAddress <> ''                
		  AND E.AdmPersonId IN (SELECT Distinct Id FROM @TempPersonIds) 

Select distinct(EmailAddress),FullName from  @TempPersonEmail where EmailAddress like '%@%.%' 
Select distinct(EmailAddress),FullName from  @TempPersonEmail where EmailAddress not like '%@%.%'

--Please Comment the above two select statements in Qa and test environments and uncomment the following two select statements

--Select 'lmcanulty@partners.org' as EmailAddress,FullName from  @TempPersonEmail where EmailAddress like '%@%.%' 
--Select 'lmcanulty@partners.org'as EmailAddress,FullName from  @TempPersonEmail where EmailAddress not like '%@%.%'
                         
END         




GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Creating [dbo].[GetPendingItemsSummary]'
GO
/************************************************************************************************        
* Name:  GetPendingItemsSummary                                                         
* Purpose: Stored procedure for retrieving the set of pending items(protocolProcess Ids with status of        
*  'Pending', 'Deferred', 'Hold', 'Req. Mod.') on Protocols that have status of        
*  'Active', 'Hold', or 'Hold-Lapsed'        
*           
*  This also returns processes that are pending (have status of pending); this means        
*  they have been submitted to Rex, but have not returned from Rex        
*        
* PARAMETERS          
* Name   Description        
* ------------------------- -----------------------------        
* @domainuserid   FwkDomainUserId of the user whose pending items need to be retrieved      
************************************************************************************************/        
        
CREATE procedure [dbo].[GetPendingItemsSummary]-- 103100      
(        
@delimittedString ntext,        
@domainUserId  int                      
)                        
AS BEGIN                        
SET NOCOUNT ON                        
                        
declare @protocolIds table (Sequence int identity, [ID] int,[ProtocolId] int)                          
insert into @protocolIds select [Id],[Value] from [GetValueTableOfDelimittedString] (@delimittedString,',')                          
        
-- constants        
declare @protocolResourceType int        
set @protocolResourceType = 2        
        
declare @keyGiverAccessLevel int        
set @keyGiverAccessLevel = 2        
        
declare @pendingProcessStatus varchar(256)        
set @pendingProcessStatus = 'PPSTATUS_PEND'        
        
declare @submittedProcessStatus varchar(256)        
set @submittedProcessStatus = 'PPSTATUS_SUBMT'        
        
declare @authorizedProtocols table (ResourceId int, AccessLevel int)        
insert into @authorizedProtocols         
select * from fnadmqgetauthorizedresourcelist (@domainuserid, @protocolResourceType)        
        
select         
 fct.ProtocolSubmissionId as 'SubmissionId',        
 fct.BoardReviewId,        
 spon.[name] as 'SponsorName',        
 fct.ProtocolId ,        
 ara.AccessLevel,        
 fct.FormsID,        
 prt.Title,        
 prt.ProtocolNumber,        
 pip.lastname + ', ' +  pip.firstname as 'PiName',        
 pip.[Id] as 'PiPersonId',        
 fct.SubmissionDate,        
 fct.BoardName,        
 fct.ReviewType,        
 fct.MeetingDate,        
 fct.BoardStatus,        
 posty.[Name] as 'OverallStatus',        
 prt.IsLocked,        
 prt.PIFwkDomainOrganizationId as 'OrganizationId',          
 prt.PiPersonId,        
 prt.ExpirationDate,        
 fct.Notification,        
 prt.Version,        
 fct.ProtocolProcessId        
        
from @authorizedProtocols ara         
inner join PendingApplications_Fct fct        
on ara.Resourceid = fct.Fwkresourceid      
inner join @protocolIds pids      
on pids.[ProtocolId] =  fct.ProtocolId        
inner join Protocol prt        
on prt.[Id] = pids.[ProtocolId]        
inner join ProtocolOverallStatusType posty        
on posty.[id] = prt.[OverallStatusId]        
left join AdmPerson pip        
on prt.pipersonid = pip.[id]        
left join AdmSponsor spon        
on prt.Admsponsorid = spon.[id]        
where ara.AccessLevel !=  @keyGiverAccessLevel        
        
union        
        
select        
 null as 'SubmissionId',        
 null as 'BoardReviewId',        
 spon.[name] as 'SponsorName',        
 pp.ProtocolId ,        
 ara.AccessLevel,        
 pp.[Name] as 'FormsID',        
 prt.Title,        
 prt.ProtocolNumber,        
 pip.lastname + ', ' +  pip.firstname as 'PiName',        
 pip.[Id] as 'PiPersonId',        
 pp.ReceivedDate as 'SubmissionDate', -- todo: this will be a field on the protocolProcess at some point        
 null as 'BoardName',        
 null as 'ReviewType',        
 null as 'MeetingDate',        
 null as 'BoardStatus',        
 'Pending' as 'OverallStatus',        
 pp.Locked as 'IsLocked',        
 prt.PIFwkDomainOrganizationId as 'OrganizationId',          
 prt.PiPersonId,        
 pp.ExpirationDate,        
 0 as 'Notification',        
 prt.Version,        
 pp.[Id] as 'ProtocolProcessId'        
        
from @authorizedProtocols ara       
inner join Protocol prt        
on ara.Resourceid = prt.Fwkresourceid      
inner join @protocolIds pids      
On  pids.[ProtocolId] =  prt.[Id]          
inner join ProtocolProcess pp        
on pp.ProtocolId = prt.[Id]        
left join AdmSponsor spon        
on prt.Admsponsorid = spon.[id]        
left join AdmPerson pip        
on prt.pipersonid = pip.[id]        
        
where        
ara.AccessLevel !=  @keyGiverAccessLevel        
and (pp.Status = @pendingProcessStatus        
or pp.Status = @submittedProcessStatus)        
and prt.MarkForDeletion = 0        
-- Pending Processes that have already made it to Rex and back will be in the ProtocolSubmission        
-- table as well, and we don't want both records to show up        
and not exists (Select ProtocolProcessId from ProtocolSubmission where ProtocolProcessId = pp.[Id])        
        
--order by protocolnumber desc        
        
select max(enddate) as 'lastfeedrundate'        
from SvcFeedRun        
where svcfeedtypeid in (select [Id] from SvcFeedType where [Name] = 'NewProtocol_RexToAsset')        
and svcfeedstatustypeid in (select [Id] from SvcFeedStatusType where [Name] = 'Completed')        
        
end        

GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Creating [dbo].[GetProtocols]'
GO
/******************************************************************                    
* Name:   [GetProtocols]  
* Purpose:  Retrieves corresponding Protocol deatils matching the Protocol Ids.        
*                    
* PARAMETERS(IN)                    
* Name    Description                         
* -------------     -------------------------------------------                    
* @delimittedString    ntext of delimitted string  
* @domainUserId		   FrameworkDomainUserId of the looged in(or Impersonated) user-Required  
*********************************************************************/                    
                    
CREATE PROCEDURE [dbo].GetProtocols  
(                    
@delimittedString ntext,    
@domainUserId  int                  
)                    
AS BEGIN                    
SET NOCOUNT ON                    
                    
Declare @protocolIds table (Sequence int identity, [ID] int,[ProtocolId] int)                      
insert into @protocolIds select [Id],[Value] from [GetValueTableOfDelimittedString] (@delimittedString,',')                      
                 
select protocol.[id]      
  ,protocol.title               
  ,protocol.expirationdate      
  ,case when len(protocol.SubStatusId) > 0 then      
   status.[name] + ', ' + substatus.[Name]       
   else status.[name] end as 'overallstatus'      
  ,protocol.pendingirb      
  ,piperson.lastname + ', ' +  piperson.firstname as 'piname'      
  ,protocol.protocolnumber      
  ,sponsor.[Name] as 'SponsorName'       
  ,protocol.PIFwkDomainOrganizationId as 'OrganizationId'        
  ,protocol.PiPersonId      
  ,protocol.Version      
  ,ara.AccessLevel       
  ,count(document.[Id]) as ConsentCount      
  ,cast((case when count(process.[Id]) = 0 then '0' else '1' end) as bit) as IsLegacy      
  ,protocol.IsLocked      
 from @protocolIds protocolTemp    
 Inner Join Protocol    
 On protocolTemp.[ProtocolId]= protocol.[Id]    
  inner join dbo.fnadmqgetauthorizedresourcelist(@domainUserId, 2) ara       
   on ara.resourceid = protocol.fwkresourceid       
  inner join ProtocolOverallStatusType status      
   on protocol.OverallStatusId = status.[id]      
  left join ProtocolSubStatusType substatus      
   on protocol.SubStatusId = substatus.[id]      
  left join admperson piperson      
   on piperson.[id] = protocol.PIPersonId      
  left join admsponsor sponsor      
   on protocol.admsponsorid = sponsor.[id]      
  left join ProtocolDocument document      
   on protocol.[Id] = document.ProtocolId and      
     document.iscurrent = 1 and document.type='ATCHTYPE_CNSNTFRM' and document.HardCopy = 0 and document.published = 1      
  left join ProtocolProcess process      
   on protocol.[Id] = process.ProtocolId and process.Type = 'PPTYPE_IR'      
 group by protocol.[id]      
  ,protocol.title               
  ,protocol.expirationdate      
  ,protocol.SubStatusId      
  ,status.[name]      
  ,substatus.[Name]       
  ,protocol.pendingirb      
  ,piperson.lastname      
  ,piperson.firstname      
  ,protocol.protocolnumber      
  ,sponsor.[Name]      
  ,protocol.PIFwkDomainOrganizationId      
  ,protocol.PiPersonId      
  ,protocol.Version      
  ,ara.AccessLevel       
  ,protocol.IsLocked  
  ,protocolTemp.[Id]   
 order by protocolTemp.[Id]      
                    
END 

GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Altering [dbo].[GetWIPProtocolProcessIds]'
GO
/******************************************************************      
* Name:   GetWIPProtocolProcessIds      
* Purpose:  Retrieves the details(from multiple tables using joins) according to the filter parameters      
*      
* PARAMETERS      
* Name        Description           
* -------------    -------------------------------------------      
* @domainUserId           Domain User ID (REQUIRED)        
* @protocolNumber   Protocol number tied up with a protocol      
* @protocolTitle   Title for the protocol      
* @pIId     PI Person Id      
* @organizationIds   Organization for a protocol      
* @sortColumn varchar(150) = 'SubmittedDate',    
* @sortOrder bit = 1-->Asc, 0-->Desc     
******************************************************************/      
ALTER PROCEDURE [dbo].[GetWIPProtocolProcessIds] --103100,'H',null,null,null,null,'LastModifiedBy'  
(      
@domainUserId int,  
@moduleType char(1) = 'H',      
@protocolNumber  VARCHAR(12)=null,      
@protocolTitle VARCHAR(1024)=null,      
@pIId INT=null,      
@organizationIds VARCHAR(4000)=null,    
@sortColumn varchar(150) = 'ProtocolNumber',    
@sortOrder bit = 1-->Asc, 0-->Desc   
    
)      
      
AS BEGIN      
      
SET NOCOUNT ON      
      
 if(@protocolNumber is null)      
  Set @protocolNumber='%'      
 else      
  Set @protocolNumber=@protocolNumber+'%'       
       
 if(@protocolTitle is null)      
  Set @protocolTitle='%'      
 else      
  Set @protocolTitle=@protocolTitle+'%'       
      
       
  DECLARE @protocolresourcetypeid varchar(2)      
  set @protocolresourcetypeid = (select [id] from FwkResourceType where [Name] = 'Protocol')      
      
  declare @keyGiverAccessLevel int      
  set @keyGiverAccessLevel = 2     
    
 --The following table serves the sorting which otherwise will make the query really big    
 Declare @tempWIPProtocolProcesses table     
 (    
  ProtocolProcessId int,    
  ProtocolNumber VARCHAR(12),    
  ProtocolId int,    
  Title VARCHAR(1024),    
  ShortTitle varchar(60),    
  [ProtocolType] varchar(20),    
  Createdate Datetime,    
  LastModifiedDate DateTime,      
  LastModifiedBy Varchar(200),      
  PIName varchar(200),    
  SponsorName varchar(150),    
  RefMeaning varchar(150),    
  AccessLevel int      
 )    
      
 if (@organizationIds is null)      
      
 BEGIN      
  Insert Into @tempWIPProtocolProcesses SELECT  pp.[Id] as ProtocolProcessId,      
    p.ProtocolNumber,      
    p.[Id] as ProtocolId,      
    p.Title,      
    p.ShortTitle,      
    pp.Type,        
    pp.CreateDate,      
    pp.LastModifiedDate,    
    (rtrim(ltrim(admp.LastName)) +', '+rtrim(ltrim(admp.FirstName)) )as LastModifieBy,      
    (rtrim(ltrim(adp.LastName)) +', '+rtrim(ltrim(adp.FirstName))) as PIName,      
    (rtrim(ltrim(ads.[Name]))) as Sponsor,      
    (CASE rtrim(ltrim(pp.[Name])) WHEN '' THEN rtrim(ltrim(rfc.RefMeaning)) ELSE rtrim(ltrim(rfc.RefMeaning))+' ('+rtrim(ltrim(pp.[Name]))+')' END) as RefMeaning,       
    arl.AccessLevel      
        
   FROM Protocol p       
        
   INNER JOIN dbo.fnAdmQGetAuthorizedResourceList(@domainUserId, @protocolresourcetypeid) arl      
    on arl.resourceid = p.fwkresourceid       
   LEFT JOIN dbo.protocolProcess pp       
    ON p.[Id]=pp.ProtocolId      
   LEFT JOIN dbo.RefCode rfc      
    ON rfc.[RefCode]=pp.Type      
   LEFT JOIN dbo.ADMPerson adp      
    ON adp.[Id]=p.PIPersonId           
   LEFT JOIN dbo.ADMPerson admp      
    ON admp.[FwkDomainUserId]=pp.LastModifiedByUserId      
        
   LEFT JOIN dbo.ADMSponsor ads      
    ON ads.[Id]=p.ADMSponsorId      
   LEFT JOIN dbo.FWKDomainOrganization FDO      
    ON FDO.[Id]=p.PIFwkDomainOrganizationId         
   WHERE       
    p.ModuleType = @moduleType    
    AND ISNULL(p.ProtocolNumber,'*')like @protocolNumber      
    AND ISNULL(p.Title, '*') like @protocolTitle      
    AND ISNULL(CAST(p.PIPersonId AS VARCHAR(20)),'*')like ISNULL(CAST(@pIID AS VARCHAR(20)), '%')      
    AND pp.Status='PPSTATUS_WIP'      
    AND P.MarkForDeletion = 0          and arl.AccessLevel !=  @keyGiverAccessLevel        
        
 END      
 ELSE      
 BEGIN      
       
   Declare @#TempCosIdTable Table([Id] int Primary Key,[Value] Varchar(4))      
   Insert Into @#TempCosIdTable  select * from GetTableOfDelimittedString(@organizationIds,'|')      
       
  Insert Into @tempWIPProtocolProcesses     
   SELECT  pp.[Id] as ProtocolProcessId,      
    p.ProtocolNumber,      
    p.[Id] as ProtocolId,      
    p.Title,      
    p.ShortTitle,      
    pp.Type,      
    pp.CreateDate,      
    pp.LastModifiedDate,    
    (rtrim(ltrim(admp.LastName)) +', '+rtrim(ltrim(admp.FirstName)) )as LastModifieBy,      
    (rtrim(ltrim(adp.LastName)) +', '+rtrim(ltrim(adp.FirstName))) as PIName,      
    (rtrim(ltrim(ads.[Name]))) as Sponsor,      
    (CASE rtrim(ltrim(pp.[Name])) WHEN '' THEN rtrim(ltrim(rfc.RefMeaning)) ELSE rfc.RefMeaning+' ('+rtrim(ltrim(pp.[Name]))+')' END) as RefMeaning,       
    arl.AccessLevel      
        
   FROM Protocol p       
        
   INNER JOIN dbo.fnAdmQGetAuthorizedResourceList(@domainUserId, @protocolresourcetypeid) arl      
    on arl.resourceid = p.fwkresourceid       
   LEFT JOIN dbo.protocolProcess pp       
    ON p.[Id]=pp.ProtocolId      
   LEFT JOIN dbo.RefCode rfc      
    ON rfc.[RefCode]=pp.Type      
   LEFT JOIN dbo.ADMPerson adp      
    ON adp.[Id]=p.PIPersonId      
   LEFT JOIN dbo.ADMPerson admp      
    ON admp.[Id]=pp.LastModifiedByUserId      
   LEFT JOIN dbo.ADMSponsor ads      
    ON ads.[Id]=p.ADMSponsorId      
   LEFT JOIN dbo.FWKDomainOrganization FDO      
    ON FDO.[Id]=p.PIFwkDomainOrganizationId      
        
   WHERE       
    p.ModuleType = @moduleType    
    AND  ISNULL(p.ProtocolNumber,'*')like @protocolNumber        
    AND ISNULL(p.Title, '*') like @protocolTitle      
    AND ISNULL(CAST(p.PIPersonId AS VARCHAR(20)),'*')like ISNULL(CAST(@pIID AS VARCHAR(20)), '%')      
    AND ISNULL(CAST(FDO.[Id]AS varchar(4)),'*')IN (Select Value from @#TempCosIdTable)      
    AND pp.Status='PPSTATUS_WIP'      
    AND P.MarkForDeletion = 0      
    AND arl.AccessLevel !=  @keyGiverAccessLevel     
         
 END     
     
 If exists (Select 1 from @tempWIPProtocolProcesses)    
  BEGIN    
   if @sortColumn = 'CreateDate' or @sortColumn = 'LastModifiedDate'      
    BEGIN    
    Select ProtocolProcessId    
     From @tempWIPProtocolProcesses    
     order by     
      case @sortOrder     
       When 0 then     
        case @SortColumn    
         when 'CreateDate' then Createdate    
         when 'LastModifiedDate' then LastmodifiedDate                                          
         end     
       End Desc,           
      case @sortOrder    
       When 1 then    
        case @SortColumn    
         when 'CreateDate' then Createdate    
         when 'LastModifiedDate' then LastmodifiedDate                       
         end          
       END    
    END       
  ELse    
   BEGIN    
    Select ProtocolProcessId    
     From @tempWIPProtocolProcesses    
     order by     
      case @sortOrder     
       When 0 then     
        case @SortColumn    
         when 'ProtocolNumber' then ProtocolNumber    
         when 'Title' then Title    
         when 'RefMeaning' then RefMeaning    
         when 'PIName' then PIName  
   when 'lastModifiedBy' then LastModifiedBy     
         else ProtocolNumber    
         end     
       End Desc,           
      case @sortOrder    
       When 1 then    
        case @SortColumn    
         when 'ProtocolNumber' then ProtocolNumber    
         when 'Title' then Title    
         when 'RefMeaning' then RefMeaning    
         when 'PIName' then PIName  
		 when 'lastModifiedBy' then LastModifiedBy     
         else ProtocolNumber                   
         end          
       END    
   END    
     
  END    
    
END      
      
    
    
  
  

GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Creating [dbo].[GetExpenseInfo_Category_Totals]'
GO


CREATE procedure [dbo].[GetExpenseInfo_Category_Totals]
(   @SessionID varchar(100),
	@domainUserID int,
	@includeProgramProjects bit = null,
	@fundNumber varchar(8) = null,
	@folderNumber varchar(16) = null,
	@bicsNumber varchar(10) = null,
	@walkerNumber varchar(10) = null,
	@sponsorNumber varchar(32) = null,
	@sponsorName varchar(64) = null,
	@sponsorTypeID int = null,
	@agreementTypeID int = null,
	@activityCode varchar(4)= null,
	@locationID int = null,
	@budgetStartDate datetime = null,
	@budgetEndDate datetime = null,
	@projectStartDate datetime = null,
	@projectEndDate datetime = null,
	@piID int = null,
	@chiefCodeList varchar(1000) = null,
	@sponsorGroupTypeID int = null,
	@budgetEndingDays int = null,
	@projectEndingDays int = null,
	@fundCreatedDays int = null,
	@lowBalance decimal(17,2) = null,
	@highBalance decimal(17,2) = null,
	@agreementStatusTypeList varchar(50)= null,
	@fundStatusTypeID int	= null,
	@categoryID int = null,
	@accountNumber varchar(10) = null,
	@expenseDateFrom datetime = null,
	@expenseDateTo datetime = null,
	@incomingFundNumber varchar(8) = null,
	@monthEndingDate datetime = null
)
as
begin
	set nocount on

	declare @accountID int
	if isnull(@accountNumber,'') = ''
		set @accountID = 0
	else
		set @accountID = (select Id from FinAccount where Number = @accountNumber)

	set @includeProgramProjects = isnull(@includeProgramProjects, 0)
	set @fundNumber = isnull(@fundNumber, '')
	set @folderNumber = isnull(@folderNumber, '')
	set @bicsNumber = isnull(@bicsNumber, '')
	set @walkerNumber = isnull(@walkerNumber, '')
	set @sponsorNumber = isnull(@sponsorNumber, '')
	set @sponsorName = isnull(@sponsorName, '')
	set @sponsorTypeID = isnull(@sponsorTypeID, 0)
	set @agreementTypeID = isnull(@agreementTypeID, 0)
	set @activityCode = isnull(@activityCode, '')
	set @locationID = isnull(@locationID, 0)
	set @budgetStartDate = isnull(@budgetStartDate, '01/01/1900')
	set @budgetEndDate = isnull(@budgetEndDate, '01/01/1900')
	set @projectStartDate = isnull(@projectStartDate, '01/01/1900')
	set @projectEndDate = isnull(@projectEndDate, '01/01/1900')
	set @piID = isnull(@piID, 0)
	set @chiefCodeList = isnull(@chiefCodeList, '')
	set @sponsorGroupTypeID = isnull(@sponsorGroupTypeID, 0)
	set @budgetEndingDays = isnull(@budgetEndingDays, 0)
	set @projectEndingDays = isnull(@projectEndingDays, 0)
	set @fundCreatedDays = isnull(@fundCreatedDays, 0)
	set @lowBalance = isnull(@lowBalance, -922337203685477)
	set @highBalance = isnull(@highBalance, 922337203685477)
	set @agreementStatusTypeList = isnull(@agreementStatusTypeList, '')
	set @fundStatusTypeID = isnull(@fundStatusTypeID, 1)
	set @categoryID = isnull(@categoryID, 0)
	set @accountID = isnull(@accountID, 0)
	set @incomingFundNumber = isnull(@incomingFundNumber, '')
	set @monthEndingDate = isnull(@monthEndingDate, '')

	declare @directCosts int
	set @directCosts = 2

	declare @indirectCosts int
	set @indirectCosts = 3

	declare @revenue int
	set @revenue = 1

	declare @TotalCost int
	set @TotalCost = 4

	declare @CashBalance int
	set @CashBalance = 5

	declare @awardedBudgetTypeId int
	set @awardedBudgetTypeId = 3

	declare @viewFinancialInfoBitValue int
	set @viewFinancialInfoBitValue = 4

	declare @viewPendingAgreementsBitValue int 
	set @viewPendingAgreementsBitValue = 32

	declare @authorizedRightsBitMask int
	set @authorizedRightsBitMask = @viewFinancialInfoBitValue + @viewPendingAgreementsBitValue

	declare @t0 datetime
	set @t0 = current_timestamp

	-- Compute the fund ID based on whether or not the invocation is from an overview or detail context. In the former case,
	-- the @incomingFundNumber is not specified. In the later case, the specified fund number will only be accepted for
	-- further processing only if the specified user has access to that fund.

	declare @fundID int
	if (@incomingFundNumber = '')
		set @fundId = 0
	else
	begin
		select @fundID = [ID] from AgrFund where FundNumber = @incomingFundNumber
		if not exists(select 1 from dbo.CheckFundAccess(@domainUserID, @fundID))
		begin
			declare @message varchar(255)
			set @message = 'User does not have access to fund number ' + @incomingFundNumber
			raiserror(@message, 16, 1)
			return
		end
	end

	-- Generate a list of funds that are accessible to the specified user. When in the detail context, there would only
	-- be one fund to worry about. Since this list of accessible funds is used multiple times, the list is stored in
	-- a table variable.

	create table #accessibleFunds (FundID int primary key, AccessLevel int default 0)

	IF OBJECT_ID('tempdb..#TempFundCollection') is not null drop table #TempFundCollection
	create table #TempFundCollection (FundID int not null, AccessLevel int not null)

	If (@incomingFundNumber = '') begin
		exec GetFundCollection @SessionId, @domainUserID
		Create Unique Index FundId on #TempFundCollection (FundId)
	end
	else
		insert into #TempFundCollection (FundID,AccessLevel) values (@fundID,32767)

	insert into #accessibleFunds
		select * from #TempFundCollection

--	if (@incomingFundNumber = '')
--		insert into #accessibleFunds
--			exec FilterFunds @domainUserID, @authorizedRightsBitMask, @includeProgramProjects,
--				@fundNumber, @folderNumber, @bicsNumber, @walkerNumber, @sponsorNumber, @sponsorName,
--				@sponsorTypeID, @agreementTypeID, @activityCode, @locationID, @budgetStartDate, @budgetEndDate,
--				@projectStartDate, @projectEndDate, @piID, @chiefCodeList, @sponsorGroupTypeID,
--				@budgetEndingDays, @projectEndingDays, @fundCreatedDays, @lowBalance, @highBalance,
--				@agreementStatusTypeList, @fundStatusTypeID
--	else
--		insert into #accessibleFunds (FundID) values (@fundID)

	declare @t1 datetime
	set @t1 = current_timestamp
	print 'Step_1: ' + cast(datediff(ss, @t0, @t1) as varchar)

	-- The expense date range should be from the first day of the 'from' month/year to the last day of the 'to' month/year.
	-- The 'to' date is clamped to the first day of the current month/year.
	-- There are three scenairos to handle:
	-- 1. Both dates are specified
	-- 2. Neither dates are specified
	-- 3. One of the dates is specified
	-- 3a. If the 'from' date is specified, the 'to' date is the mininum of the last gl close date and the 'from' + 12 months
	-- 3b. If the 'to' date is specified, the 'from' date is 'to' - 12 months

	Declare @refreshDatesTable table (glPostAsOfDate datetime,salaryAsOfDate datetime, poapAsOfDate datetime)

	Insert into @refreshDatesTable Exec GetRefreshDates

	Declare @glPostAsOfDate DateTime
	select @glPostAsOfDate = glPostAsOfDate from @refreshDatesTable

	if ((@expenseDateTo is null) or (@expenseDateTo > @glPostAsOfDate))
		set @expenseDateTo = @glPostAsOfDate

	if (@expenseDateFrom is null)
		set @expenseDateFrom = '01/01/1900'		--dateadd(day, 1, dateadd(month, -12, @expenseDateTo))
	else
		set @expenseDateFrom = dateadd(day, -datepart(day, @expenseDateFrom) + 1, @expenseDateFrom)

	-- Retrieve the list of month-end dates between the from and to date range. This is saved in a table variable
	-- for later reuse.
	create table #dateRange ([ID] int primary key identity(1, 1), MonthEndingDate datetime)

	insert into #dateRange
		select Dates from dbo.GetDateRanges(@expenseDateFrom, @expenseDateTo)

	declare @t2 datetime
	set @t2 = current_timestamp
	print 'Step_2: ' + cast(datediff(ss, @t1, @t2) as varchar)

--start
	declare  @FinAccts table (CategoryID int, CategoryName varchar(50), 
		AccountID int, AccountNumber varchar(50), SortOrder int)

	insert into  @FinAccts
	select distinct fc.[ID],
			fc.[Name],
			fa.[ID],
			fa.Number + ' - ' + [Description],
			fc.SortOrder
	from 
		FinAccount fa 
		inner join FinCategory fc on fc.[ID] = fa.FinCategoryID

	where fc.[Name] not in ('INDIRECT COSTS', 'INVESTMENT INCOME', 'OTHER INCOME')
	and (fc.[ID] = @categoryID or @categoryID = 0) 
	and (fa.ID = @accountID or @accountID = 0)


	if @expenseDateFrom = '1900-01-01 00:00:00'
	begin
		declare @firstMonthWithExpenses datetime
		set @firstMonthWithExpenses = (
			select top 1 MonthEndingDate  
				from MonthlyFundAccountActuals mfaa
				inner join @FinAccts fa on mfaa.AccountID = fa.AccountID
				inner join #accessibleFunds af on mfaa.FundID = af.FundID 
				where mfaa.Amount <> 0
				order by MonthEndingDate Asc)

		delete	#dateRange
		where	MonthEndingDate < @firstMonthWithExpenses
		set @expenseDateFrom = @firstMonthWithExpenses
	end


	select  CategoryID,  CategoryName, SortOrder,
		Sum(mfaa.Amount) as ExpenseAmount
		from 
			MonthlyFundAccountActuals mfaa
			join @FinAccts fa on mfaa.AccountID = fa.AccountID
			join #accessibleFunds af on mfaa.FundID = af.FundID
			join #dateRange dr on mfaa.MonthEndingDate = dr.MonthEndingDate 
		group by SortOrder, CategoryID, CategoryName 
		order by SortOrder


	drop table #dateRange
	drop table #accessibleFunds
end






GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Altering [dbo].[GetActiveInactiveProtocolIds]'
GO
/************************************************************************************************                            
* Name  : GetActiveInactiveProtocolIdsTest                                                                                      
* Purpose: This stored procedure retrieves the actives/ Inactive Protocol matching                       
*     the search criteria                          
*                              
* PARAMETERS                              
* Name   Description                            
* ------------------------- -----------------------------                            
* @domainuserid    -FrameworkDomainUserId                              
* @originatingpage   -Page Initiating the Procedure                            
* @protocolNo    -Protocol number(Search Criteria)                            
* @protocolTitle   -Protocol Title (Serach criteria)                            
* @sponsorName    -Spnosor name (Search criteria)                            
* @versionNo    -Verson number (Sercah criteria)                            
* @expDateFrom DateTime  -expiry Date From (Search Criteria)                            
* @expDateTo    -Expiry Date To (Search Criteria)                            
* @piId      -PI Id (Search criteria)                            
* @cosIds     -CosIds (Serach Criteria)                            
* @sortColumn    -SortColumn(SubmissionDate-Default)                      
* @sortOrder    -Sort Order for the result set (bit=1-->Desc,0-->Ascending)                      
*                            
************************************************************************************************                            
*Call: [GetProtocolSummaryIds] 103100,0                            
************************************************************************************************/                               
ALTER procedure [dbo].[GetActiveInactiveProtocolIds] --103100,1,'H'                           
(                              
 @domainuserid int,                              
 @originatingpage int,          
 @module char(1)= 'H',                            
 @protocolNo varchar(12)= null,                            
 @protocolTitle varchar(1024)= null,                            
 @sponsorName varchar(75)= null,                            
 @versionNo varchar(100)= null,                            
 @expDateFrom DateTime = null,                            
 @expDateTo DateTime = null,                            
 @piId Int=null,                            
 @cosIds ntext = null,    
 @species varchar = null,    
 @isRadioIsotope bit = 0,    
 @isBiologicalAgent bit = 0,    
 @isToxicChemicals bit = 0,    
 @isTissueTest bit = 0,                            
 @sortColumn varchar(150)= 'SubmissionDate',                                                  
 @sortOrder bit=1-->Asc,0-->Desc                                        
)                               
as                              
begin                              
set nocount on                              
                              
 declare @activepage int                              
 declare @inactivepage int                              
                              
 set @activepage = 0                              
 set @inactivepage = 1                              
                              
 declare @activestatustypeid varchar(1)                              
 declare @holdstatustypeid varchar(1)                              
 declare @holdlapsedstatustypeid varchar(1)                               
 declare @inactivestatustypeid varchar(1)                              
 declare @terminatedstatustypeid varchar(1)                              
                               
 set @activestatustypeid = 1                              
 set @holdstatustypeid = 4                              
 set @holdlapsedstatustypeid = 9                              
 set @inactivestatustypeid = 2                              
 set @terminatedstatustypeid = 7                             
                            
                            
 if  @protocolNo is  null                           
  Set @protocolNo = '%'                            
 else                            
  Set @protocolNo = @protocolNo + '%'                            
                            
 if  @protocolTitle is null                            
  Set @protocolTitle = '%'            
 else                            
  Set @protocolTitle = @protocolTitle + '%'               
                            
 if @sponsorName is null                            
  Set @sponsorName = '%'                            
 Else                             
  Set @sponsorName = @sponsorName + '%'                            
                            
 if @versionNo is null                            
  Set @versionNo =  '%'                            
 Else                             
  Set @versionNo = @versionNo + '%'                            
                            
  declare @protocolresourcetypeid varchar(1)                              
  select @protocolresourcetypeid = [Id] from FwkResourceType where [Name] = 'Protocol'                   
                              
  declare @keyGiverAccessLevel int                              
  set @keyGiverAccessLevel = 2                              
                              
  -- obtain the desired protocol statuses for the calling context                              
  declare @statustable table                              
  (                               
   status int not null                              
  )                              
                              
  if @originatingpage = @activepage                               
   begin                              
    insert into @statustable values (@activestatustypeid)                              
    if (@@error <> 0)                              
  begin                              
   raiserror('insert into @statustable failed', 16, 1)                              
   return                              
  end                              
    insert into @statustable values (@holdstatustypeid)                              
    if (@@error <> 0)                              
  begin                              
   raiserror('insert into @statustable failed', 16, 1)                              
   return                              
  end                              
    insert into @statustable values (@holdlapsedstatustypeid)                              
    if (@@error <> 0)                              
  begin                              
   raiserror('insert into @statustable failed', 16, 1)                              
   return                              
  end                              
   end                              
                              
  else if @originatingpage = @inactivepage                               
   begin                              
    insert into @statustable values (@inactivestatustypeid)                              
    if (@@error <> 0)                              
  begin                              
   raiserror('insert into @statustable failed', 16, 1)                              
   return                              
  end                              
    insert into @statustable values (@terminatedstatustypeid)                              
    if (@@error <> 0)                              
  begin                              
   raiserror('insert into @statustable failed', 16, 1)                              
   return                              
  end                              
   end                              
                              
  else                              
   begin                              
    raiserror('wrong originating context', 16, 1)                              
    return                              
   end                           
                           
  if @cosIds is null                            
BEGIN                           
                        
 select                            
 protocol.[id] as ProtocolId                          
    from protocol                              
     inner join dbo.fnadmqgetauthorizedresourcelist(@domainuserid, @protocolresourcetypeid) ara                 
      on ara.resourceid = protocol.fwkresourceid                               
     inner join ProtocolOverallStatusType status                              
      on protocol.OverallStatusId = status.[id]                              
     left join ProtocolSubStatusType substatus                              
      on protocol.SubStatusId = substatus.[id]                              
     left join admperson piperson                 
      on piperson.[id] = protocol.PIPersonId                              
     left join admsponsor sponsor                              
      on protocol.admsponsorid = sponsor.[id]                              
     left join ProtocolDocument document                              
      on protocol.[Id] = document.ProtocolId and                              
     document.iscurrent = 1 and document.type='ATCHTYPE_CNSNTFRM' and document.HardCopy = 0 and document.published = 1                              
     left join ProtocolProcess process                              
      on protocol.[Id] = process.ProtocolId and process.Type = 'PPTYPE_IR'                          
 inner join @statustable stc                          
 On  protocol.OverallStatusId =  stc.status                            
    where  protocol.isCurrent = 1    
  and protocol.moduleType = @module  
  and  ara.AccessLevel !=  @keyGiverAccessLevel                           
   and IsNull(protocol.Title,'*') like @protocolTitle                            
   and IsNull(protocol.version,'*') like @versionNo                            
   and IsNull(Protocol.protocolnumber,'*') like @protocolNo                            
   and ((IsNull(Protocol.ExpirationDate,'1/1/1900') >= IsNull(@expDateFrom, '1/1/1900')) and (IsNull(Protocol.ExpirationDate,'1/1/1900') <= IsNull(@expDateTo,'12/31/2099')))                            
   and IsNull(sponsor.Name,'*') like @sponsorName                            
   and IsNull(cast(protocol.PiPersonId as varchar(20)),'*') like isNull(cast(@piId as varchar(20)),'%')                            
   and IsNull(protocol.SpeciesCode , '*') like IsNull (@species,'%')    
   and (protocol.RadioIsotope = @isRadioIsotope  
        or 0 = @isRadioIsotope)  
   and (protocol.BiologicalAgent = @isBiologicalAgent  
        or 0 = @isBiologicalAgent)  
   and (protocol.ToxicChem = @isToxicChemicals  
        or 0 = @isToxicChemicals)  
   and (protocol.TissueTest = @isTissueTest  
        or 0 = @isTissueTest)  
                             
     Order by CASE @SortOrder                            
     When 0 then                              
      CASE @SortColumn                             
    WHEN 'Title' THEN Protocol.[Title]                                      
    When 'PIName' Then piperson.[lastname]                            
    When 'SponsorName' Then Sponsor.[name]                             
    When 'OverallStatus' Then Status.[name]+','+substatus.[Name]                                                                                          
    When 'ProtocolNumber' THEN protocol.[ProtocolNumber]                            
    --Else Protocol.Title                            
    END                    
      END Desc,                     
     CASE @SortOrder                            
      When 0 then                      
      CASE @SortColumn                             
    When 'SubmissionDate' Then Protocol.[SubmissionDate]                             
    When 'ExpirationDate' Then Protocol.[ExpirationDate]                             
    ELSE Protocol.[SubmissionDate]                      
    END                                 
     END Desc,                            
      CASE @SortOrder                            
   When 1 then                             
      CASE @SortColumn                          
     WHEN 'Title' THEN Protocol.[Title]                                      
     When 'PIName' Then piperson.[lastname]                        
     When 'SponsorName' Then Sponsor.[name]                             
     When 'OverallStatus' Then Status.[name]+','+substatus.[Name]                                                                                            
     When 'ProtocolNumber' THEN protocol.[ProtocolNumber]                            
     --Else Protocol.Title                            
      END                      
     END ASC,                    
    CASE @SortOrder                      
     When 1 then                      
      case @SortColumn                              
     When 'SubmissionDate' Then Protocol.[SubmissionDate]                             
     When 'ExpirationDate' Then Protocol.[ExpirationDate]                             
     ELSE Protocol.[SubmissionDate]                    
      END                                
   END                         
  END                      
  Else                            
  BEGIN                            
     --Filter the results based on the CosIds along with other search criteria if exists                            
    declare @CosIdtable table            
  (                               
   cosId int not null                              
  )                              
    Insert into @CosIdtable Select value from [GetValueTableOfDelimittedString](@cosIds,',')                           
                                
     select                            
    protocol.[id] as ProtocolId                          
    from protocol                              
     inner join dbo.fnadmqgetauthorizedresourcelist(@domainuserid, @protocolresourcetypeid) ara                               
     on ara.resourceid = protocol.fwkresourceid                               
    inner join ProtocolOverallStatusType status                              
     on protocol.OverallStatusId = status.[id]                              
    left join ProtocolSubStatusType substatus                              
     on protocol.SubStatusId = substatus.[id]                 
    inner join admperson piperson                              
     on piperson.[id] = protocol.PIPersonId                              
    left join admsponsor sponsor                              
     on protocol.admsponsorid = sponsor.[id]                              
    left join ProtocolDocument document                              
     on protocol.[Id] = document.ProtocolId and                              
    document.iscurrent = 1 and document.type='ATCHTYPE_CNSNTFRM' and document.HardCopy = 0 and document.published = 1                              
    left join ProtocolProcess process                              
     on protocol.[Id] = process.ProtocolId and process.Type = 'PPTYPE_IR'                            
    Inner Join @CosIdtable costable                            
     On  costable.cosId = protocol.PIFwkDomainOrganizationId                         
    inner join @statustable stc                          
     On  protocol.OverallStatusId =  stc.status                             
   where  protocol.isCurrent = 1  
  and  ara.AccessLevel !=  @keyGiverAccessLevel   
 and protocol.moduleType = @module                                               
    and IsNull(protocol.Title,'%') like @protocolTitle                            
    and IsNull(protocol.version,'%') like @versionNo                            
    and IsNull(Protocol.protocolnumber,'%') like @protocolNo                            
    and ((IsNull(Protocol.ExpirationDate,'1/1/1900') >= IsNull(@expDateFrom, '1/1/1900')) and (IsNull(Protocol.ExpirationDate,'1/1/1900') <= IsNull(@expDateTo,'12/31/2099')))                            
    and IsNull(sponsor.Name,'%') like @sponsorName                            
    and cast(protocol.PiPersonId as varchar(20)) like isNull(cast(@piId as varchar(20)),'%')    
   and IsNull(protocol.SpeciesCode , '*') like IsNull(@species,'%')    
   and (protocol.RadioIsotope = @isRadioIsotope  
        or 0 = @isRadioIsotope)  
   and (protocol.BiologicalAgent = @isBiologicalAgent  
        or 0 = @isBiologicalAgent)  
   and (protocol.ToxicChem = @isToxicChemicals  
        or 0 = @isToxicChemicals)  
   and (protocol.TissueTest = @isTissueTest  
        or 0 = @isTissueTest)  
                        
   Order by CASE @SortOrder                            
     When 0 then                              
     CASE @SortColumn                             
   WHEN 'Title' THEN Protocol.[Title]                                      
   When 'PIName' Then piperson.[lastname]                            
   When 'SponsorName' Then Sponsor.[name]                             
   When 'OverallStatus' Then Status.[name]+','+substatus.[Name]                                                                                           
   When 'ProtocolNumber' THEN protocol.[ProtocolNumber]                            
   --Else Protocol.Title                            
   END                    
     END Desc,                     
    CASE @SortOrder                            
     When 0 then                      
     CASE @SortColumn                             
   When 'SubmissionDate' Then Protocol.[SubmissionDate]                             
   When 'ExpirationDate' Then Protocol.[ExpirationDate]                             
   ELSE Protocol.[SubmissionDate]                      
   END                                 
    END Desc,                            
     CASE @SortOrder                            
    When 1 then                             
   CASE @SortColumn                             
     WHEN 'Title' THEN Protocol.[Title]                                      
     When 'PIName' Then piperson.[lastname]                        
     When 'SponsorName' Then Sponsor.[name]                          
     When 'OverallStatus' Then Status.[name]+','+substatus.[Name]                                                                                            
     When 'ProtocolNumber' THEN protocol.[ProtocolNumber]                            
     --Else Protocol.Title             
   END                           
     END ASC,                    
   CASE @SortOrder                      
    When 1 then                      
     case @SortColumn                              
    When 'SubmissionDate' Then Protocol.[SubmissionDate]                             
    When 'ExpirationDate' Then Protocol.[ExpirationDate]                             
    ELSE Protocol.[SubmissionDate]                    
     END                                
    END                        
  END                   
END                              

GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Creating [dbo].[GetExpenseInfo_FinType_Month]'
GO




CREATE procedure [dbo].[GetExpenseInfo_FinType_Month]
(   @SessionID varchar(100),
	@domainUserID int,
	@includeProgramProjects bit = null,
	@fundNumber varchar(8) = null,
	@folderNumber varchar(16) = null,
	@bicsNumber varchar(10) = null,
	@walkerNumber varchar(10) = null,
	@sponsorNumber varchar(32) = null,
	@sponsorName varchar(64) = null,
	@sponsorTypeID int = null,
	@agreementTypeID int = null,
	@activityCode varchar(4)= null,
	@locationID int = null,
	@budgetStartDate datetime = null,
	@budgetEndDate datetime = null,
	@projectStartDate datetime = null,
	@projectEndDate datetime = null,
	@piID int = null,
	@chiefCodeList varchar(1000) = null,
	@sponsorGroupTypeID int = null,
	@budgetEndingDays int = null,
	@projectEndingDays int = null,
	@fundCreatedDays int = null,
	@lowBalance decimal(17,2) = null,
	@highBalance decimal(17,2) = null,
	@agreementStatusTypeList varchar(50)= null,
	@fundStatusTypeID int	= null,
	@categoryID int = null,
	@accountNumber varchar(10) = null,
	@expenseDateFrom datetime = null,
	@expenseDateTo datetime = null,
	@incomingFundNumber varchar(8) = null,
	@monthEndingDate datetime = null
)
as
begin
	set nocount on

	declare @accountID int
	if isnull(@accountNumber,'') = ''
		set @accountID = 0
	else
		set @accountID = (select Id from FinAccount where Number = @accountNumber)

	set @includeProgramProjects = isnull(@includeProgramProjects, 0)
	set @fundNumber = isnull(@fundNumber, '')
	set @folderNumber = isnull(@folderNumber, '')
	set @bicsNumber = isnull(@bicsNumber, '')
	set @walkerNumber = isnull(@walkerNumber, '')
	set @sponsorNumber = isnull(@sponsorNumber, '')
	set @sponsorName = isnull(@sponsorName, '')
	set @sponsorTypeID = isnull(@sponsorTypeID, 0)
	set @agreementTypeID = isnull(@agreementTypeID, 0)
	set @activityCode = isnull(@activityCode, '')
	set @locationID = isnull(@locationID, 0)
	set @budgetStartDate = isnull(@budgetStartDate, '01/01/1900')
	set @budgetEndDate = isnull(@budgetEndDate, '01/01/1900')
	set @projectStartDate = isnull(@projectStartDate, '01/01/1900')
	set @projectEndDate = isnull(@projectEndDate, '01/01/1900')
	set @piID = isnull(@piID, 0)
	set @chiefCodeList = isnull(@chiefCodeList, '')
	set @sponsorGroupTypeID = isnull(@sponsorGroupTypeID, 0)
	set @budgetEndingDays = isnull(@budgetEndingDays, 0)
	set @projectEndingDays = isnull(@projectEndingDays, 0)
	set @fundCreatedDays = isnull(@fundCreatedDays, 0)
	set @lowBalance = isnull(@lowBalance, -922337203685477)
	set @highBalance = isnull(@highBalance, 922337203685477)
	set @agreementStatusTypeList = isnull(@agreementStatusTypeList, '')
	set @fundStatusTypeID = isnull(@fundStatusTypeID, 1)
	set @categoryID = isnull(@categoryID, 0)
	set @accountID = isnull(@accountID, 0)
	set @incomingFundNumber = isnull(@incomingFundNumber, '')
	set @monthEndingDate = isnull(@monthEndingDate, '')

	declare @directCosts int
	set @directCosts = 2

	declare @indirectCosts int
	set @indirectCosts = 3

	declare @revenue int
	set @revenue = 1

	declare @TotalCost int
	set @TotalCost = 4

	declare @CashBalance int
	set @CashBalance = 5

	declare @awardedBudgetTypeId int
	set @awardedBudgetTypeId = 3

	declare @viewFinancialInfoBitValue int
	set @viewFinancialInfoBitValue = 4

	declare @viewPendingAgreementsBitValue int 
	set @viewPendingAgreementsBitValue = 32

	declare @authorizedRightsBitMask int
	set @authorizedRightsBitMask = @viewFinancialInfoBitValue + @viewPendingAgreementsBitValue

	declare @t0 datetime
	set @t0 = current_timestamp

	-- Compute the fund ID based on whether or not the invocation is from an overview or detail context. In the former case,
	-- the @incomingFundNumber is not specified. In the later case, the specified fund number will only be accepted for
	-- further processing only if the specified user has access to that fund.

	declare @fundID int
	if (@incomingFundNumber = '')
		set @fundId = 0
	else
	begin
		select @fundID = [ID] from AgrFund where FundNumber = @incomingFundNumber
		if not exists(select 1 from dbo.CheckFundAccess(@domainUserID, @fundID))
		begin
			declare @message varchar(255)
			set @message = 'User does not have access to fund number ' + @incomingFundNumber
			raiserror(@message, 16, 1)
			return
		end
	end

	-- Generate a list of funds that are accessible to the specified user. When in the detail context, there would only
	-- be one fund to worry about. Since this list of accessible funds is used multiple times, the list is stored in
	-- a table variable.

	create table #accessibleFunds (FundID int primary key, AccessLevel int default 0)

	IF OBJECT_ID('tempdb..#TempFundCollection') is not null drop table #TempFundCollection
	create table #TempFundCollection (FundID int not null, AccessLevel int not null)

	If (@incomingFundNumber = '') begin
		exec GetFundCollection @SessionId, @domainUserID
		Create Unique Index FundId on #TempFundCollection (FundId)
	end
	else
		insert into #TempFundCollection (FundID,AccessLevel) values (@fundID,32767)

	insert into #accessibleFunds
		select * from #TempFundCollection

--	if (@incomingFundNumber = '')
--		insert into #accessibleFunds
--			exec FilterFunds @domainUserID, @authorizedRightsBitMask, @includeProgramProjects,
--				@fundNumber, @folderNumber, @bicsNumber, @walkerNumber, @sponsorNumber, @sponsorName,
--				@sponsorTypeID, @agreementTypeID, @activityCode, @locationID, @budgetStartDate, @budgetEndDate,
--				@projectStartDate, @projectEndDate, @piID, @chiefCodeList, @sponsorGroupTypeID,
--				@budgetEndingDays, @projectEndingDays, @fundCreatedDays, @lowBalance, @highBalance,
--				@agreementStatusTypeList, @fundStatusTypeID
--	else
--		insert into #accessibleFunds (FundID) values (@fundID)

	declare @t1 datetime
	set @t1 = current_timestamp
	print 'Step_1: ' + cast(datediff(ss, @t0, @t1) as varchar)

	-- The expense date range should be from the first day of the 'from' month/year to the last day of the 'to' month/year.
	-- The 'to' date is clamped to the first day of the current month/year.
	-- There are three scenairos to handle:
	-- 1. Both dates are specified
	-- 2. Neither dates are specified
	-- 3. One of the dates is specified
	-- 3a. If the 'from' date is specified, the 'to' date is the mininum of the last gl close date and the 'from' + 12 months
	-- 3b. If the 'to' date is specified, the 'from' date is 'to' - 12 months

	Declare @refreshDatesTable table (glPostAsOfDate datetime,salaryAsOfDate datetime, poapAsOfDate datetime)

	Insert into @refreshDatesTable Exec GetRefreshDates

	Declare @glPostAsOfDate DateTime
	select @glPostAsOfDate = glPostAsOfDate from @refreshDatesTable

	if ((@expenseDateTo is null) or (@expenseDateTo > @glPostAsOfDate))
		set @expenseDateTo = @glPostAsOfDate

	if (@expenseDateFrom is null)
		set @expenseDateFrom = '01/01/1900'		--dateadd(day, 1, dateadd(month, -12, @expenseDateTo))
	else
		set @expenseDateFrom = dateadd(day, -datepart(day, @expenseDateFrom) + 1, @expenseDateFrom)

	-- Retrieve the list of month-end dates between the from and to date range. This is saved in a table variable
	-- for later reuse.
	create table #dateRange ([ID] int primary key identity(1, 1), MonthEndingDate datetime)

	insert into #dateRange
		select Dates from dbo.GetDateRanges(@expenseDateFrom, @expenseDateTo)

	declare @t2 datetime
	set @t2 = current_timestamp
	print 'Step_2: ' + cast(datediff(ss, @t1, @t2) as varchar)

--start
	declare  @FinAccts table (CategoryID int, CategoryName varchar(50), 
		AccountID int, AccountNumber varchar(50), SortOrder int)

	insert into  @FinAccts
	select distinct fc.[ID],
			fc.[Name],
			fa.[ID],
			fa.Number + ' - ' + [Description],
			fc.SortOrder
	from 
		FinAccount fa 
		inner join FinCategory fc on fc.[ID] = fa.FinCategoryID
		INNER join MonthlyFundAccountActuals mfaa on mfaa.AccountID = fa.ID
		Inner join #accessibleFunds af on mfaa.FundID = af.FundID
		Inner join #DateRange dr on mfaa.MonthEndingDate = dr.MonthEndingDate
	where fc.[Name] not in ('INDIRECT COSTS', 'INVESTMENT INCOME', 'OTHER INCOME')
	and (fc.[ID] = @categoryID or @categoryID = 0) 
	and (fa.ID = @accountID or @accountID = 0)


	if @expenseDateFrom = '1900-01-01 00:00:00'
	begin
		declare @firstMonthWithExpenses datetime
		set @firstMonthWithExpenses = (
			select Min( mfaa.MonthEndingDate )
				from MonthlyFundAccountActuals mfaa
				inner join @FinAccts fa on mfaa.AccountID = fa.AccountID
				inner join #accessibleFunds af on mfaa.FundID = af.FundID 
				right outer join #dateRange dr on mfaa.MonthEndingDate = dr.MonthEndingDate 
				where mfaa.Amount <> 0
				)

		delete	#dateRange
		where	MonthEndingDate < @firstMonthWithExpenses
		set @expenseDateFrom = @firstMonthWithExpenses
	end


	declare @t3 datetime
	set @t3 = current_timestamp
	print 'Step_3: ' + cast(datediff(ss, @t2, @t3) as varchar)

	-- Retrieve direct cost information. This information will be used to generate multiple tables in the resultset and as such
	-- is stored in a table variable.
	create table #directCosts (ExpenseAmount money, ExpenseMonth datetime)

	insert into #directCosts

-- Sixth resultset
		select
			sum(isnull(mfa.Amount, 0)) as ExpenseAmount,
			dr.MonthEndingDate as ExpenseMonth
	   	from 
			MonthlyFundActuals mfa
			inner join #accessibleFunds af on mfa.FundID = af.FundID
			right outer join #dateRange dr on mfa.MonthEndingDate = dr.MonthEndingDate
				and mfa.FinancialTypeID = @directCosts
				and ((isnull(mfa.FundID, 0) = @fundID) or (@fundID = 0))
				and mfa.MonthEndingDate between @expenseDateFrom and @expenseDateTo
		group by
			dr.MonthEndingDate with ROLLUP

	select * from #directCosts

	
	-- Retrieve revenue information. This information will be used to generate multiple tables in the resultset and as such
	-- is stored in a table variable. This table is populated here to use for direct cost balances even though its data is
	-- not returned until later - see below, tenth table.
	create table #revenue (ExpenseAmount money, ExpenseMonth datetime)
	create index ExpenseMonth on #revenue(ExpenseMonth)
--select 0 as ExpenseAmount, convert(DateTime, getdate(), 101) as ExpenseMonth
		
	-- The tenth table in the resultset is the revenue for each expense month and the aggregate of such total costs
	-- for all of the expense months.
	insert into #revenue
		select
			sum(isnull(-mfa.Amount, 0)) as ExpenseAmount,
			dr.MonthEndingDate as ExpenseMonth
	   	from 
			MonthlyFundActuals mfa
			inner join #accessibleFunds af on mfa.FundID = af.FundID
			right outer join #dateRange dr on mfa.MonthEndingDate = dr.MonthEndingDate
				and mfa.FinancialTypeID = @Revenue
				and ((isnull(mfa.FundID, 0) = @fundID) or (@fundID = 0))
				and mfa.MonthEndingDate between @expenseDateFrom and @expenseDateTo
		group by
			dr.MonthEndingDate with rollup
		
	

	create table #directCostBalance (ExpenseAmount money, ExpenseMonth datetime)
	create index ExpenseMonth on #directCostBalance(ExpenseMonth)

	insert into #directCostBalance
		select r.ExpenseAmount - d.ExpenseAmount, r.ExpenseMonth
		from #revenue r inner join #directCosts d on r.ExpenseMonth = d.ExpenseMonth
	

	select ExpenseAmount, convert(DateTime, ExpenseMonth, 101) as ExpenseMonth from #directCostBalance
	union all
	select isnull(sum(ExpenseAmount), 0) as ExpenseAmount, null as ExpenseMonth from #directCostBalance


	create table #indirectCosts (ExpenseAmount money, ExpenseMonth datetime)

	insert into #indirectCosts

-- Eighth

		select
			sum(isnull(mfa.Amount, 0)) as ExpenseAmount,
			dr.MonthEndingDate as ExpenseMonth
	   	from 
			MonthlyFundActuals mfa
			inner join #accessibleFunds af on mfa.FundID = af.FundID
			right outer join #dateRange dr on mfa.MonthEndingDate = dr.MonthEndingDate
				and mfa.FinancialTypeID = @indirectCosts
				and ((isnull(mfa.FundID, 0) = @fundID) or (@fundID = 0))
				and mfa.MonthEndingDate between @expenseDateFrom and @expenseDateTo
		group by
			dr.MonthEndingDate with rollup

select * from #indirectCosts

	-- Retrieve total cost information. This information will be used to generate multiple tables in the resultset and as such
	-- is stored in a table variable.
	create table #totalCosts (ExpenseAmount money, ExpenseMonth datetime)

	insert into #totalCosts

		select
			sum(isnull(mfa.Amount, 0)) as ExpenseAmount,
			dr.MonthEndingDate as ExpenseMonth
	   	from 
			MonthlyFundActuals mfa
			inner join #accessibleFunds af on mfa.FundID = af.FundID
			right outer join #dateRange dr on mfa.MonthEndingDate = dr.MonthEndingDate
				and mfa.FinancialTypeID = @TotalCost
				and ((isnull(mfa.FundID, 0) = @fundID) or (@fundID = 0))
				and mfa.MonthEndingDate between @expenseDateFrom and @expenseDateTo
		group by
			dr.MonthEndingDate with rollup
	select * from #totalCosts

	select * from #revenue

	-- Retrieve cash balance information. This information will be used to generate multiple tables in the resultset and as such
	-- is stored in a table variable.
	create table #cashBalance (ExpenseAmount money, ExpenseMonth datetime)

	insert into #cashBalance
		select
			-(sum(isnull(revenue.AmountTodate, 0))+sum(isnull(DirectCost.AmountTodate, 0))+sum(isnull(IndirectCost.AmountTodate, 0))) as ExpenseAmount,
			dr.MonthEndingDate as ExpenseMonth
	   	from 
			#accessibleFunds af
			cross join #dateRange dr 
			left outer join MonthlyFundActuals Revenue on Revenue.FundID = af.FundID and Revenue.FinancialTypeID = @revenue 
						 and Revenue.MonthEndingDate = 	(Select max(Revenue1.MonthEndingDate) from MonthlyFundActuals Revenue1 
														 where Revenue1.fundid = Revenue.fundid 
																and Revenue1.FinancialTypeID = Revenue.FinancialTypeID 
																and Revenue1.MonthEndingDate <= dr.MonthEndingDate)

			left outer join MonthlyFundActuals IndirectCost on IndirectCost.FundID = af.FundID and IndirectCost.FinancialTypeID = @indirectCosts 
						and IndirectCost.MonthEndingDate = (Select max(IndirectCost1.MonthEndingDate) from MonthlyFundActuals IndirectCost1 
														 where IndirectCost1.fundid = IndirectCost.fundid 
																and IndirectCost1.FinancialTypeID = IndirectCost.FinancialTypeID 
																and IndirectCost1.MonthEndingDate <= dr.MonthEndingDate)

			left outer join MonthlyFundActuals DirectCost on DirectCost.FundID = af.FundID and DirectCost.FinancialTypeID = @directCosts 
						and DirectCost.MonthEndingDate =(Select max(DirectCost1.MonthEndingDate) from MonthlyFundActuals DirectCost1 
														 where DirectCost1.fundid = DirectCost.fundid 
																and DirectCost1.FinancialTypeID = DirectCost.FinancialTypeID 
																and DirectCost1.MonthEndingDate <= dr.MonthEndingDate)
		group by
			dr.MonthEndingDate
		order by
			dr.MonthEndingDate

	-- The eleventh table in the resultset is the cash balance for each expense month and the aggregate of such total costs
	-- for all of the expense months.
	select ExpenseAmount, convert(DateTime, ExpenseMonth, 101) as ExpenseMonth from #cashBalance
	union all
	select isnull(ExpenseAmount, 0) as ExpenseAmount, null as ExpenseMonth from #cashBalance 
	where expensemonth = (select max(b.expensemonth) from #cashbalance b)
	
	if (@incomingFundNumber <> '')
		exec dbo.GetProjectHeader @incomingFundNumber, null

	-- Retrieve grand total information.
	select
		dc.ExpenseAmount as DirectCostsTotal,
		dcb.ExpenseAmount as DirectCostBalanceTotal,
		ic.ExpenseAmount as IndirectCostsTotal,
		tc.ExpenseAmount as TotalCostsTotal,
		r.ExpenseAmount as RevenueTotal,
		cb.ExpenseAmount as CashBalanceTotal
	from
		(select ExpenseAmount from #directCosts where ExpenseMonth is null) dc,
		(select isnull(sum(ExpenseAmount), 0) as ExpenseAmount from #directCostBalance) dcb,
		(select ExpenseAmount from #indirectCosts where ExpenseMonth is null) ic,
		(select ExpenseAmount from #totalCosts where ExpenseMonth is null) tc,
		(select ExpenseAmount from #revenue where ExpenseMonth is null) r,
		(select isnull(ExpenseAmount, 0) as ExpenseAmount from #cashBalance
		 where expensemonth = (select max(b.expensemonth) from #cashbalance b)) cb

--		(select isnull(sum(ExpenseAmount), 0) as ExpenseAmount from #directCosts) dc,
--		--(select isnull(sum(ExpenseAmount), 0) as ExpenseAmount from #directCostBalance) dcb,
--		(select isnull(sum(ExpenseAmount), 0) as ExpenseAmount from #indirectCosts) ic,
--		(select isnull(sum(ExpenseAmount), 0) as ExpenseAmount from #totalCosts) tc,
--		(select isnull(sum(ExpenseAmount), 0) as ExpenseAmount from #revenue) r,
--		(select isnull(ExpenseAmount, 0) as ExpenseAmount from #cashBalance
--		 where expensemonth = (select max(b.expensemonth) from #cashbalance b)) cb


	drop table #cashBalance
	drop table #indirectCosts
	drop table #directCostBalance
	drop table #revenue
	drop table #directCosts
	drop table #totalCosts
	--drop table #accountCategory
	--drop table #lookUp
	drop table #dateRange
	drop table #accessibleFunds
end








GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Altering [dbo].[GetActiveOrInactiveProtocols]'
GO
/******************************************************************                    
* Name:   [GetActiveOrInactiveProtocols]  
* Purpose:  Retrieves corresponding Protocol deatils matching the Protocol Ids.        
*                    
* PARAMETERS(IN)                    
* Name    Description                         
* -------------     -------------------------------------------                    
* @delimittedString    ntext of delimitted string  
* @domainUserId		   FrameworkDomainUserId of the looged in(or Impersonated) user-Required  
*********************************************************************/                    
                    
ALTER PROCEDURE [dbo].GetActiveOrInactiveProtocols  
(                    
@delimittedString ntext,    
@domainUserId  int                  
)                    
AS BEGIN                    
SET NOCOUNT ON                    
                    
Declare @protocolIds table (Sequence int identity, [ID] int,[ProtocolId] int)                      
insert into @protocolIds select [Id],[Value] from [GetValueTableOfDelimittedString] (@delimittedString,',')                      
                 
select protocol.[id]      
  ,protocol.title               
  ,protocol.expirationdate      
  ,case when len(protocol.SubStatusId) > 0 then      
   status.[name] + ', ' + substatus.[Name]       
   else status.[name] end as 'overallstatus'      
  ,protocol.pendingirb      
  ,piperson.lastname + ', ' +  piperson.firstname as 'piname'      
  ,protocol.protocolnumber      
  ,sponsor.[Name] as 'SponsorName'       
  ,protocol.PIFwkDomainOrganizationId as 'OrganizationId'        
  ,protocol.PiPersonId      
  ,protocol.Version      
  ,ara.AccessLevel       
  ,count(document.[Id]) as ConsentCount      
  ,cast((case when count(process.[Id]) = 0 then '0' else '1' end) as bit) as IsLegacy      
  ,protocol.IsLocked      
 from @protocolIds protocolTemp    
 Inner Join Protocol    
 On protocolTemp.[ProtocolId]= protocol.[Id]    
  inner join dbo.fnadmqgetauthorizedresourcelist(@domainUserId, 2) ara       
   on ara.resourceid = protocol.fwkresourceid       
  inner join ProtocolOverallStatusType status      
   on protocol.OverallStatusId = status.[id]      
  left join ProtocolSubStatusType substatus      
   on protocol.SubStatusId = substatus.[id]      
  left join admperson piperson      
   on piperson.[id] = protocol.PIPersonId      
  left join admsponsor sponsor      
   on protocol.admsponsorid = sponsor.[id]      
  left join ProtocolDocument document      
   on protocol.[Id] = document.ProtocolId and      
     document.iscurrent = 1 and document.type='ATCHTYPE_CNSNTFRM' and document.HardCopy = 0 and document.published = 1      
  left join ProtocolProcess process      
   on protocol.[Id] = process.ProtocolId and process.Type = 'PPTYPE_IR'      
 group by protocol.[id]      
  ,protocol.title               
  ,protocol.expirationdate      
  ,protocol.SubStatusId      
  ,status.[name]      
  ,substatus.[Name]       
  ,protocol.pendingirb      
  ,piperson.lastname      
  ,piperson.firstname      
  ,protocol.protocolnumber      
  ,sponsor.[Name]      
  ,protocol.PIFwkDomainOrganizationId      
  ,protocol.PiPersonId      
  ,protocol.Version      
  ,ara.AccessLevel       
  ,protocol.IsLocked  
  ,protocolTemp.[Id]   
 order by protocolTemp.[Id]      
                    
END 

GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Creating [dbo].[GetExpenseInfo_Account_Category_Totals]'
GO


CREATE procedure [dbo].[GetExpenseInfo_Account_Category_Totals]
(	@SessionID varchar(100),
	@domainUserID int,
	@includeProgramProjects bit = null,
	@fundNumber varchar(8) = null,
	@folderNumber varchar(16) = null,
	@bicsNumber varchar(10) = null,
	@walkerNumber varchar(10) = null,
	@sponsorNumber varchar(32) = null,
	@sponsorName varchar(64) = null,
	@sponsorTypeID int = null,
	@agreementTypeID int = null,
	@activityCode varchar(4)= null,
	@locationID int = null,
	@budgetStartDate datetime = null,
	@budgetEndDate datetime = null,
	@projectStartDate datetime = null,
	@projectEndDate datetime = null,
	@piID int = null,
	@chiefCodeList varchar(1000) = null,
	@sponsorGroupTypeID int = null,
	@budgetEndingDays int = null,
	@projectEndingDays int = null,
	@fundCreatedDays int = null,
	@lowBalance decimal(17,2) = null,
	@highBalance decimal(17,2) = null,
	@agreementStatusTypeList varchar(50)= null,
	@fundStatusTypeID int	= null,
	@categoryID int = null,
	@accountNumber varchar(10) = null,
	@expenseDateFrom datetime = null,
	@expenseDateTo datetime = null,
	@incomingFundNumber varchar(8) = null,
	@monthEndingDate datetime = null
)
as
begin
	set nocount on

	declare @accountID int
	if isnull(@accountNumber,'') = ''
		set @accountID = 0
	else
		set @accountID = (select Id from FinAccount where Number = @accountNumber)

	set @includeProgramProjects = isnull(@includeProgramProjects, 0)
	set @fundNumber = isnull(@fundNumber, '')
	set @folderNumber = isnull(@folderNumber, '')
	set @bicsNumber = isnull(@bicsNumber, '')
	set @walkerNumber = isnull(@walkerNumber, '')
	set @sponsorNumber = isnull(@sponsorNumber, '')
	set @sponsorName = isnull(@sponsorName, '')
	set @sponsorTypeID = isnull(@sponsorTypeID, 0)
	set @agreementTypeID = isnull(@agreementTypeID, 0)
	set @activityCode = isnull(@activityCode, '')
	set @locationID = isnull(@locationID, 0)
	set @budgetStartDate = isnull(@budgetStartDate, '01/01/1900')
	set @budgetEndDate = isnull(@budgetEndDate, '01/01/1900')
	set @projectStartDate = isnull(@projectStartDate, '01/01/1900')
	set @projectEndDate = isnull(@projectEndDate, '01/01/1900')
	set @piID = isnull(@piID, 0)
	set @chiefCodeList = isnull(@chiefCodeList, '')
	set @sponsorGroupTypeID = isnull(@sponsorGroupTypeID, 0)
	set @budgetEndingDays = isnull(@budgetEndingDays, 0)
	set @projectEndingDays = isnull(@projectEndingDays, 0)
	set @fundCreatedDays = isnull(@fundCreatedDays, 0)
	set @lowBalance = isnull(@lowBalance, -922337203685477)
	set @highBalance = isnull(@highBalance, 922337203685477)
	set @agreementStatusTypeList = isnull(@agreementStatusTypeList, '')
	set @fundStatusTypeID = isnull(@fundStatusTypeID, 1)
	set @categoryID = isnull(@categoryID, 0)
	set @accountID = isnull(@accountID, 0)
	set @incomingFundNumber = isnull(@incomingFundNumber, '')
	set @monthEndingDate = isnull(@monthEndingDate, '')

	declare @directCosts int
	set @directCosts = 2

	declare @indirectCosts int
	set @indirectCosts = 3

	declare @revenue int
	set @revenue = 1

	declare @TotalCost int
	set @TotalCost = 4

	declare @CashBalance int
	set @CashBalance = 5

	declare @awardedBudgetTypeId int
	set @awardedBudgetTypeId = 3

	declare @viewFinancialInfoBitValue int
	set @viewFinancialInfoBitValue = 4

	declare @viewPendingAgreementsBitValue int 
	set @viewPendingAgreementsBitValue = 32

	declare @authorizedRightsBitMask int
	set @authorizedRightsBitMask = @viewFinancialInfoBitValue + @viewPendingAgreementsBitValue

	declare @t0 datetime
	set @t0 = current_timestamp

	-- Compute the fund ID based on whether or not the invocation is from an overview or detail context. In the former case,
	-- the @incomingFundNumber is not specified. In the later case, the specified fund number will only be accepted for
	-- further processing only if the specified user has access to that fund.

	declare @fundID int
	if (@incomingFundNumber = '')
		set @fundId = 0
	else
	begin
		select @fundID = [ID] from AgrFund where FundNumber = @incomingFundNumber
		if not exists(select 1 from dbo.CheckFundAccess(@domainUserID, @fundID))
		begin
			declare @message varchar(255)
			set @message = 'User does not have access to fund number ' + @incomingFundNumber
			raiserror(@message, 16, 1)
			return
		end
	end

	-- Generate a list of funds that are accessible to the specified user. When in the detail context, there would only
	-- be one fund to worry about. Since this list of accessible funds is used multiple times, the list is stored in
	-- a table variable.

	create table #accessibleFunds (FundID int primary key, AccessLevel int default 0)

	IF OBJECT_ID('tempdb..#TempFundCollection') is not null drop table #TempFundCollection
	create table #TempFundCollection (FundID int not null, AccessLevel int not null)

	If (@incomingFundNumber = '') begin
		exec GetFundCollection @SessionId, @domainUserID
		Create Unique Index FundId on #TempFundCollection (FundId)
	end
	else
		insert into #TempFundCollection (FundID,AccessLevel) values (@fundID,32767)

	insert into #accessibleFunds
		select * from #TempFundCollection

--	if (@incomingFundNumber = '')
--		insert into #accessibleFunds
--			exec FilterFunds @domainUserID, @authorizedRightsBitMask, @includeProgramProjects,
--				@fundNumber, @folderNumber, @bicsNumber, @walkerNumber, @sponsorNumber, @sponsorName,
--				@sponsorTypeID, @agreementTypeID, @activityCode, @locationID, @budgetStartDate, @budgetEndDate,
--				@projectStartDate, @projectEndDate, @piID, @chiefCodeList, @sponsorGroupTypeID,
--				@budgetEndingDays, @projectEndingDays, @fundCreatedDays, @lowBalance, @highBalance,
--				@agreementStatusTypeList, @fundStatusTypeID
--	else
--		insert into #accessibleFunds (FundID) values (@fundID)

	declare @t1 datetime
	set @t1 = current_timestamp
	print 'Step_1: ' + cast(datediff(ss, @t0, @t1) as varchar)

	-- The expense date range should be from the first day of the 'from' month/year to the last day of the 'to' month/year.
	-- The 'to' date is clamped to the first day of the current month/year.
	-- There are three scenairos to handle:
	-- 1. Both dates are specified
	-- 2. Neither dates are specified
	-- 3. One of the dates is specified
	-- 3a. If the 'from' date is specified, the 'to' date is the mininum of the last gl close date and the 'from' + 12 months
	-- 3b. If the 'to' date is specified, the 'from' date is 'to' - 12 months

	Declare @refreshDatesTable table (glPostAsOfDate datetime,salaryAsOfDate datetime, poapAsOfDate datetime)

	Insert into @refreshDatesTable Exec GetRefreshDates

	Declare @glPostAsOfDate DateTime
	select @glPostAsOfDate = glPostAsOfDate from @refreshDatesTable

	if ((@expenseDateTo is null) or (@expenseDateTo > @glPostAsOfDate))
		set @expenseDateTo = @glPostAsOfDate

	if (@expenseDateFrom is null)
		set @expenseDateFrom = '01/01/1900'		--dateadd(day, 1, dateadd(month, -12, @expenseDateTo))
	else
		set @expenseDateFrom = dateadd(day, -datepart(day, @expenseDateFrom) + 1, @expenseDateFrom)

	-- Retrieve the list of month-end dates between the from and to date range. This is saved in a table variable
	-- for later reuse.
	create table #dateRange ([ID] int primary key identity(1, 1), MonthEndingDate datetime)

	insert into #dateRange
		select Dates from dbo.GetDateRanges(@expenseDateFrom, @expenseDateTo)

	declare @t2 datetime
	set @t2 = current_timestamp
	print 'Step_2: ' + cast(datediff(ss, @t1, @t2) as varchar)

--start
	declare  @FinAccts table (CategoryID int, CategoryName varchar(50), 
		AccountID int, AccountNumber varchar(50), SortOrder int)

	insert into  @FinAccts
	select distinct fc.[ID],
			fc.[Name],
			fa.[ID],
			fa.Number + ' - ' + [Description],
			fc.SortOrder
	from 
		FinAccount fa 
		inner join FinCategory fc on fc.[ID] = fa.FinCategoryID

	where fc.[Name] not in ('INDIRECT COSTS', 'INVESTMENT INCOME', 'OTHER INCOME')
	and (fc.[ID] = @categoryID or @categoryID = 0) 
	and (fa.ID = @accountID or @accountID = 0)


	if @expenseDateFrom = '1900-01-01 00:00:00'
	begin
		declare @firstMonthWithExpenses datetime
		set @firstMonthWithExpenses = (
			select top 1 MonthEndingDate  
				from MonthlyFundAccountActuals mfaa
				inner join @FinAccts fa on mfaa.AccountID = fa.AccountID
				inner join #accessibleFunds af on mfaa.FundID = af.FundID 
				where mfaa.Amount <> 0
				order by MonthEndingDate Asc)

		delete	#dateRange
		where	MonthEndingDate < @firstMonthWithExpenses
		set @expenseDateFrom = @firstMonthWithExpenses
	end



--	-- The fifth table in the resultset is the agreegated expense for each account.

-- Fifth Resultset

	select
		fa.AccountID,
		fa.AccountNumber,
		fa.CategoryID,
		fa.CategoryName,
		fa.SortOrder,
		sum(mfaa.Amount) as ExpenseAmount
		from 
			MonthlyFundAccountActuals mfaa
			join @FinAccts fa on mfaa.AccountID = fa.AccountID
			join #accessibleFunds af on mfaa.FundID = af.FundID
			join #dateRange dr on mfaa.MonthEndingDate = dr.MonthEndingDate 
		group by
			fa.AccountID,fa.AccountNumber, fa.CategoryID, fa.CategoryName, fa.SortOrder
		order by
			fa.SortOrder, fa.AccountID


	
	drop table #dateRange
	drop table #accessibleFunds
end






GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Creating [dbo].[GetExpenseInfo_FinType_Month1]'
GO



CREATE procedure [dbo].[GetExpenseInfo_FinType_Month1]
(   @SessionID varchar(100),
	@domainUserID int,
	@includeProgramProjects bit = null,
	@fundNumber varchar(8) = null,
	@folderNumber varchar(16) = null,
	@bicsNumber varchar(10) = null,
	@walkerNumber varchar(10) = null,
	@sponsorNumber varchar(32) = null,
	@sponsorName varchar(64) = null,
	@sponsorTypeID int = null,
	@agreementTypeID int = null,
	@activityCode varchar(4)= null,
	@locationID int = null,
	@budgetStartDate datetime = null,
	@budgetEndDate datetime = null,
	@projectStartDate datetime = null,
	@projectEndDate datetime = null,
	@piID int = null,
	@chiefCodeList varchar(1000) = null,
	@sponsorGroupTypeID int = null,
	@budgetEndingDays int = null,
	@projectEndingDays int = null,
	@fundCreatedDays int = null,
	@lowBalance decimal(17,2) = null,
	@highBalance decimal(17,2) = null,
	@agreementStatusTypeList varchar(50)= null,
	@fundStatusTypeID int	= null,
	@categoryID int = null,
	@accountNumber varchar(10) = null,
	@expenseDateFrom datetime = null,
	@expenseDateTo datetime = null,
	@incomingFundNumber varchar(8) = null,
	@monthEndingDate datetime = null
)
as
begin
	set nocount on

	declare @accountID int
	if isnull(@accountNumber,'') = ''
		set @accountID = 0
	else
		set @accountID = (select Id from FinAccount where Number = @accountNumber)

	set @includeProgramProjects = isnull(@includeProgramProjects, 0)
	set @fundNumber = isnull(@fundNumber, '')
	set @folderNumber = isnull(@folderNumber, '')
	set @bicsNumber = isnull(@bicsNumber, '')
	set @walkerNumber = isnull(@walkerNumber, '')
	set @sponsorNumber = isnull(@sponsorNumber, '')
	set @sponsorName = isnull(@sponsorName, '')
	set @sponsorTypeID = isnull(@sponsorTypeID, 0)
	set @agreementTypeID = isnull(@agreementTypeID, 0)
	set @activityCode = isnull(@activityCode, '')
	set @locationID = isnull(@locationID, 0)
	set @budgetStartDate = isnull(@budgetStartDate, '01/01/1900')
	set @budgetEndDate = isnull(@budgetEndDate, '01/01/1900')
	set @projectStartDate = isnull(@projectStartDate, '01/01/1900')
	set @projectEndDate = isnull(@projectEndDate, '01/01/1900')
	set @piID = isnull(@piID, 0)
	set @chiefCodeList = isnull(@chiefCodeList, '')
	set @sponsorGroupTypeID = isnull(@sponsorGroupTypeID, 0)
	set @budgetEndingDays = isnull(@budgetEndingDays, 0)
	set @projectEndingDays = isnull(@projectEndingDays, 0)
	set @fundCreatedDays = isnull(@fundCreatedDays, 0)
	set @lowBalance = isnull(@lowBalance, -922337203685477)
	set @highBalance = isnull(@highBalance, 922337203685477)
	set @agreementStatusTypeList = isnull(@agreementStatusTypeList, '')
	set @fundStatusTypeID = isnull(@fundStatusTypeID, 1)
	set @categoryID = isnull(@categoryID, 0)
	set @accountID = isnull(@accountID, 0)
	set @incomingFundNumber = isnull(@incomingFundNumber, '')
	set @monthEndingDate = isnull(@monthEndingDate, '')

	declare @directCosts int
	set @directCosts = 2

	declare @indirectCosts int
	set @indirectCosts = 3

	declare @revenue int
	set @revenue = 1

	declare @TotalCost int
	set @TotalCost = 4

	declare @CashBalance int
	set @CashBalance = 5

	declare @awardedBudgetTypeId int
	set @awardedBudgetTypeId = 3

	declare @viewFinancialInfoBitValue int
	set @viewFinancialInfoBitValue = 4

	declare @viewPendingAgreementsBitValue int 
	set @viewPendingAgreementsBitValue = 32

	declare @authorizedRightsBitMask int
	set @authorizedRightsBitMask = @viewFinancialInfoBitValue + @viewPendingAgreementsBitValue

	declare @t0 datetime
	set @t0 = current_timestamp

	-- Compute the fund ID based on whether or not the invocation is from an overview or detail context. In the former case,
	-- the @incomingFundNumber is not specified. In the later case, the specified fund number will only be accepted for
	-- further processing only if the specified user has access to that fund.

	declare @fundID int
	if (@incomingFundNumber = '')
		set @fundId = 0
	else
	begin
		select @fundID = [ID] from AgrFund where FundNumber = @incomingFundNumber
		if not exists(select 1 from dbo.CheckFundAccess(@domainUserID, @fundID))
		begin
			declare @message varchar(255)
			set @message = 'User does not have access to fund number ' + @incomingFundNumber
			raiserror(@message, 16, 1)
			return
		end
	end

	-- Generate a list of funds that are accessible to the specified user. When in the detail context, there would only
	-- be one fund to worry about. Since this list of accessible funds is used multiple times, the list is stored in
	-- a table variable.

	create table #accessibleFunds (FundID int primary key, AccessLevel int default 0)

	IF OBJECT_ID('tempdb..#TempFundCollection') is not null drop table #TempFundCollection
	create table #TempFundCollection (FundID int not null, AccessLevel int not null)

	If (@incomingFundNumber = '') begin
		exec GetFundCollection @SessionId, @domainUserID
		Create Unique Index FundId on #TempFundCollection (FundId)
	end
	else
		insert into #TempFundCollection (FundID,AccessLevel) values (@fundID,32767)

	insert into #accessibleFunds
		select * from #TempFundCollection

--	if (@incomingFundNumber = '')
--		insert into #accessibleFunds
--			exec FilterFunds @domainUserID, @authorizedRightsBitMask, @includeProgramProjects,
--				@fundNumber, @folderNumber, @bicsNumber, @walkerNumber, @sponsorNumber, @sponsorName,
--				@sponsorTypeID, @agreementTypeID, @activityCode, @locationID, @budgetStartDate, @budgetEndDate,
--				@projectStartDate, @projectEndDate, @piID, @chiefCodeList, @sponsorGroupTypeID,
--				@budgetEndingDays, @projectEndingDays, @fundCreatedDays, @lowBalance, @highBalance,
--				@agreementStatusTypeList, @fundStatusTypeID
--	else
--		insert into #accessibleFunds (FundID) values (@fundID)

	declare @t1 datetime
	set @t1 = current_timestamp
	print 'Step_1: ' + cast(datediff(ss, @t0, @t1) as varchar)

	-- The expense date range should be from the first day of the 'from' month/year to the last day of the 'to' month/year.
	-- The 'to' date is clamped to the first day of the current month/year.
	-- There are three scenairos to handle:
	-- 1. Both dates are specified
	-- 2. Neither dates are specified
	-- 3. One of the dates is specified
	-- 3a. If the 'from' date is specified, the 'to' date is the mininum of the last gl close date and the 'from' + 12 months
	-- 3b. If the 'to' date is specified, the 'from' date is 'to' - 12 months

	Declare @refreshDatesTable table (glPostAsOfDate datetime,salaryAsOfDate datetime, poapAsOfDate datetime)

	Insert into @refreshDatesTable Exec GetRefreshDates

	Declare @glPostAsOfDate DateTime
	select @glPostAsOfDate = glPostAsOfDate from @refreshDatesTable

	if ((@expenseDateTo is null) or (@expenseDateTo > @glPostAsOfDate))
		set @expenseDateTo = @glPostAsOfDate

	if (@expenseDateFrom is null)
		set @expenseDateFrom = '01/01/1900'		--dateadd(day, 1, dateadd(month, -12, @expenseDateTo))
	else
		set @expenseDateFrom = dateadd(day, -datepart(day, @expenseDateFrom) + 1, @expenseDateFrom)

	-- Retrieve the list of month-end dates between the from and to date range. This is saved in a table variable
	-- for later reuse.
	create table #dateRange ([ID] int primary key identity(1, 1), MonthEndingDate datetime)

	insert into #dateRange
		select Dates from dbo.GetDateRanges(@expenseDateFrom, @expenseDateTo)

	declare @t2 datetime
	set @t2 = current_timestamp
	print 'Step_2: ' + cast(datediff(ss, @t1, @t2) as varchar)

--start
	declare  @FinAccts table (CategoryID int, CategoryName varchar(50), 
		AccountID int, AccountNumber varchar(50), SortOrder int)

	insert into  @FinAccts
	select distinct fc.[ID],
			fc.[Name],
			fa.[ID],
			fa.Number + ' - ' + [Description],
			fc.SortOrder
	from 
		FinAccount fa 
		inner join FinCategory fc on fc.[ID] = fa.FinCategoryID
		INNER join MonthlyFundAccountActuals mfaa on mfaa.AccountID = fa.ID
		Inner join #accessibleFunds af on mfaa.FundID = af.FundID
		Inner join #DateRange dr on mfaa.MonthEndingDate = dr.MonthEndingDate
	where fc.[Name] not in ('INDIRECT COSTS', 'INVESTMENT INCOME', 'OTHER INCOME')
	and (fc.[ID] = @categoryID or @categoryID = 0) 
	and (fa.ID = @accountID or @accountID = 0)


	if @expenseDateFrom = '1900-01-01 00:00:00'
	begin
		declare @firstMonthWithExpenses datetime
		set @firstMonthWithExpenses = (
			select Min( mfaa.MonthEndingDate )
				from MonthlyFundAccountActuals mfaa
				inner join @FinAccts fa on mfaa.AccountID = fa.AccountID
				inner join #accessibleFunds af on mfaa.FundID = af.FundID 
				right outer join #dateRange dr on mfaa.MonthEndingDate = dr.MonthEndingDate 
				where mfaa.Amount <> 0
				)

		delete	#dateRange
		where	MonthEndingDate < @firstMonthWithExpenses
		set @expenseDateFrom = @firstMonthWithExpenses
	end


	declare @t3 datetime
	set @t3 = current_timestamp
	print 'Step_3: ' + cast(datediff(ss, @t2, @t3) as varchar)

	-- Retrieve direct cost information. This information will be used to generate multiple tables in the resultset and as such
	-- is stored in a table variable.
	create table #directCosts (ExpenseAmount money, ExpenseMonth datetime)

	insert into #directCosts

-- Sixth resultset
		select
			sum(isnull(mfa.Amount, 0)) as ExpenseAmount,
			dr.MonthEndingDate as ExpenseMonth
	   	from 
			MonthlyFundActuals mfa
			inner join #accessibleFunds af on mfa.FundID = af.FundID
			right outer join #dateRange dr on mfa.MonthEndingDate = dr.MonthEndingDate
				and mfa.FinancialTypeID = @directCosts
				and ((isnull(mfa.FundID, 0) = @fundID) or (@fundID = 0))
				and mfa.MonthEndingDate between @expenseDateFrom and @expenseDateTo
		group by
			dr.MonthEndingDate with ROLLUP

	select * from #directCosts

	
	-- Retrieve revenue information. This information will be used to generate multiple tables in the resultset and as such
	-- is stored in a table variable. This table is populated here to use for direct cost balances even though its data is
	-- not returned until later - see below, tenth table.
	create table #revenue (ExpenseAmount money, ExpenseMonth datetime)
	create index ExpenseMonth on #revenue(ExpenseMonth)
--select 0 as ExpenseAmount, convert(DateTime, getdate(), 101) as ExpenseMonth
		
	-- The tenth table in the resultset is the revenue for each expense month and the aggregate of such total costs
	-- for all of the expense months.
	insert into #revenue
		select
			sum(isnull(-mfa.Amount, 0)) as ExpenseAmount,
			dr.MonthEndingDate as ExpenseMonth
	   	from 
			MonthlyFundActuals mfa
			inner join #accessibleFunds af on mfa.FundID = af.FundID
			right outer join #dateRange dr on mfa.MonthEndingDate = dr.MonthEndingDate
				and mfa.FinancialTypeID = @Revenue
				and ((isnull(mfa.FundID, 0) = @fundID) or (@fundID = 0))
				and mfa.MonthEndingDate between @expenseDateFrom and @expenseDateTo
		group by
			dr.MonthEndingDate with rollup
		
	

	create table #directCostBalance (ExpenseAmount money, ExpenseMonth datetime)
	create index ExpenseMonth on #directCostBalance(ExpenseMonth)

	insert into #directCostBalance
		select r.ExpenseAmount - d.ExpenseAmount, r.ExpenseMonth
		from #revenue r inner join #directCosts d on r.ExpenseMonth = d.ExpenseMonth
	

	select ExpenseAmount, convert(DateTime, ExpenseMonth, 101) as ExpenseMonth from #directCostBalance
	union all
	select isnull(sum(ExpenseAmount), 0) as ExpenseAmount, null as ExpenseMonth from #directCostBalance


	create table #indirectCosts (ExpenseAmount money, ExpenseMonth datetime)

	insert into #indirectCosts

-- Eighth

		select
			sum(isnull(mfa.Amount, 0)) as ExpenseAmount,
			dr.MonthEndingDate as ExpenseMonth
	   	from 
			MonthlyFundActuals mfa
			inner join #accessibleFunds af on mfa.FundID = af.FundID
			right outer join #dateRange dr on mfa.MonthEndingDate = dr.MonthEndingDate
				and mfa.FinancialTypeID = @indirectCosts
				and ((isnull(mfa.FundID, 0) = @fundID) or (@fundID = 0))
				and mfa.MonthEndingDate between @expenseDateFrom and @expenseDateTo
		group by
			dr.MonthEndingDate with rollup

select * from #indirectCosts

	-- Retrieve total cost information. This information will be used to generate multiple tables in the resultset and as such
	-- is stored in a table variable.
	create table #totalCosts (ExpenseAmount money, ExpenseMonth datetime)

	insert into #totalCosts

		select
			sum(isnull(mfa.Amount, 0)) as ExpenseAmount,
			dr.MonthEndingDate as ExpenseMonth
	   	from 
			MonthlyFundActuals mfa
			inner join #accessibleFunds af on mfa.FundID = af.FundID
			right outer join #dateRange dr on mfa.MonthEndingDate = dr.MonthEndingDate
				and mfa.FinancialTypeID = @TotalCost
				and ((isnull(mfa.FundID, 0) = @fundID) or (@fundID = 0))
				and mfa.MonthEndingDate between @expenseDateFrom and @expenseDateTo
		group by
			dr.MonthEndingDate with rollup
	select * from #totalCosts

	select * from #revenue

	-- Retrieve cash balance information. This information will be used to generate multiple tables in the resultset and as such
	-- is stored in a table variable.
	create table #cashBalance (ExpenseAmount money, ExpenseMonth datetime)

	insert into #cashBalance
		select
			-(sum(isnull(revenue.AmountTodate, 0))+sum(isnull(DirectCost.AmountTodate, 0))+sum(isnull(IndirectCost.AmountTodate, 0))) as ExpenseAmount,
			dr.MonthEndingDate as ExpenseMonth
	   	from 
			#accessibleFunds af
			cross join #dateRange dr 
			left outer join MonthlyFundActuals Revenue on Revenue.FundID = af.FundID and Revenue.FinancialTypeID = @revenue 
						 and Revenue.MonthEndingDate = 	(Select max(Revenue1.MonthEndingDate) from MonthlyFundActuals Revenue1 
														 where Revenue1.fundid = Revenue.fundid 
																and Revenue1.FinancialTypeID = Revenue.FinancialTypeID 
																and Revenue1.MonthEndingDate <= dr.MonthEndingDate)

			left outer join MonthlyFundActuals IndirectCost on IndirectCost.FundID = af.FundID and IndirectCost.FinancialTypeID = @indirectCosts 
						and IndirectCost.MonthEndingDate = (Select max(IndirectCost1.MonthEndingDate) from MonthlyFundActuals IndirectCost1 
														 where IndirectCost1.fundid = IndirectCost.fundid 
																and IndirectCost1.FinancialTypeID = IndirectCost.FinancialTypeID 
																and IndirectCost1.MonthEndingDate <= dr.MonthEndingDate)

			left outer join MonthlyFundActuals DirectCost on DirectCost.FundID = af.FundID and DirectCost.FinancialTypeID = @directCosts 
						and DirectCost.MonthEndingDate =(Select max(DirectCost1.MonthEndingDate) from MonthlyFundActuals DirectCost1 
														 where DirectCost1.fundid = DirectCost.fundid 
																and DirectCost1.FinancialTypeID = DirectCost.FinancialTypeID 
																and DirectCost1.MonthEndingDate <= dr.MonthEndingDate)
		group by
			dr.MonthEndingDate
		order by
			dr.MonthEndingDate

	-- The eleventh table in the resultset is the cash balance for each expense month and the aggregate of such total costs
	-- for all of the expense months.
	select ExpenseAmount, convert(DateTime, ExpenseMonth, 101) as ExpenseMonth from #cashBalance
	union all
	select isnull(ExpenseAmount, 0) as ExpenseAmount, null as ExpenseMonth from #cashBalance 
	where expensemonth = (select max(b.expensemonth) from #cashbalance b)
	
	if (@incomingFundNumber <> '')
		exec dbo.GetProjectHeader @incomingFundNumber, null

	-- Retrieve grand total information.
	select
		dc.ExpenseAmount as DirectCostsTotal,
		dcb.ExpenseAmount as DirectCostBalanceTotal,
		ic.ExpenseAmount as IndirectCostsTotal,
		tc.ExpenseAmount as TotalCostsTotal,
		r.ExpenseAmount as RevenueTotal,
		cb.ExpenseAmount as CashBalanceTotal
	from
		(select ExpenseAmount from #directCosts where ExpenseMonth is null) dc,
		(select isnull(sum(ExpenseAmount), 0) as ExpenseAmount from #directCostBalance) dcb,
		(select ExpenseAmount from #indirectCosts where ExpenseMonth is null) ic,
		(select ExpenseAmount from #totalCosts where ExpenseMonth is null) tc,
		(select ExpenseAmount from #revenue where ExpenseMonth is null) r,
		(select isnull(ExpenseAmount, 0) as ExpenseAmount from #cashBalance
		 where expensemonth = (select max(b.expensemonth) from #cashbalance b)) cb

--		(select isnull(sum(ExpenseAmount), 0) as ExpenseAmount from #directCosts) dc,
--		--(select isnull(sum(ExpenseAmount), 0) as ExpenseAmount from #directCostBalance) dcb,
--		(select isnull(sum(ExpenseAmount), 0) as ExpenseAmount from #indirectCosts) ic,
--		(select isnull(sum(ExpenseAmount), 0) as ExpenseAmount from #totalCosts) tc,
--		(select isnull(sum(ExpenseAmount), 0) as ExpenseAmount from #revenue) r,
--		(select isnull(ExpenseAmount, 0) as ExpenseAmount from #cashBalance
--		 where expensemonth = (select max(b.expensemonth) from #cashbalance b)) cb


	drop table #cashBalance
	drop table #indirectCosts
	drop table #directCostBalance
	drop table #revenue
	drop table #directCosts
	drop table #totalCosts
	--drop table #accountCategory
	--drop table #lookUp
	drop table #dateRange
	drop table #accessibleFunds
end







GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Altering [dbo].[GetWIPProtocolProcesses]'
GO
/******************************************************************                        
* Name:   GetWIPProtocolProcesses      
* Purpose:  Retrieves corresponding Protocol processIds deatils matching the ProtocolProcess Ids.            
*                        
* PARAMETERS(IN)                        
* Name    Description                             
* -------------     -------------------------------------------                        
* @delimittedString    ntext of delimitted string of protocolProcessIds     
* @domainUserId     FrameworkDomainUserId of the looged in(or Impersonated) user-Required      
*********************************************************************/                        
                        
ALTER PROCEDURE [dbo].GetWIPProtocolProcesses      
(                        
@delimittedString ntext,        
@domainUserId  int                      
)                        
AS BEGIN                        
SET NOCOUNT ON                        
                        
Declare @protocolProcessIds table (Sequence int identity, [ID] int,[ProtocolProcessId] int)                          
insert into @protocolProcessIds select [Id],[Value] from [GetValueTableOfDelimittedString] (@delimittedString,',')                          
                     
 SELECT      
 pp.[Id] as ProtocolProcessId,      
 p.ProtocolNumber,      
 p.[Id] as ProtocolId,      
 p.Title,       
 pp.Type,      
 pp.CreateDate,      
 pp.LastModifiedDate,      
 (rtrim(ltrim(admp.LastName)) +', '+rtrim(ltrim(admp.FirstName)) )as LastModifiedBy,      
 (rtrim(ltrim(adp.LastName)) +', '+rtrim(ltrim(adp.FirstName))) as PIName,      
 (rtrim(ltrim(ads.[Name]))) as Sponsor,      
 (CASE rtrim(ltrim(pp.[Name])) WHEN '' THEN rtrim(ltrim(rfc.RefMeaning)) ELSE rfc.RefMeaning+' ('+rtrim(ltrim(pp.[Name]))+')' END) as RefMeaning,       
 arl.AccessLevel,
 case when len(p.ShortTitle) > 30 then substring(p.shortTitle,1,27)+'...' else p.shortTitle end as ShortTitle            
 FROM @protocolProcessIds tempPPIds   
   
   inner JOIN dbo.protocolProcess pp       
    ON pp.[Id]=tempPPIds.ProtocolProcessId   
   Left Join Protocol p  
 ON p.Id = pp.ProtocolId     
   LEFT JOIN dbo.RefCode rfc      
    ON rfc.[RefCode]=pp.Type      
   LEFT JOIN dbo.ADMPerson adp      
    ON adp.[Id]=p.PIPersonId           
   LEFT JOIN dbo.ADMPerson admp      
    ON admp.[FwkDomainUserId]=pp.LastModifiedByUserId        
   LEFT JOIN dbo.ADMSponsor ads      
    ON ads.[Id]=p.ADMSponsorId      
   LEFT JOIN dbo.FWKDomainOrganization FDO      
    ON FDO.[Id]=p.PIFwkDomainOrganizationId   
 Inner join dbo.fnadmqgetauthorizedresourcelist(@domainUserId, 2) arl    
  ON arl.resourceid = p.fwkresourceid     
 order by tempPPIds.[Id]              
                        
END     
    
    

GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Creating [dbo].[GetExpenseInfo_Account_Category_Month_NotZero]'
GO



CREATE procedure [dbo].[GetExpenseInfo_Account_Category_Month_NotZero]
( 
	@SessionID varchar(100),
	@domainUserID int,
	@includeProgramProjects bit = null,
	@fundNumber varchar(8) = null,
	@folderNumber varchar(16) = null,
	@bicsNumber varchar(10) = null,
	@walkerNumber varchar(10) = null,
	@sponsorNumber varchar(32) = null,
	@sponsorName varchar(64) = null,
	@sponsorTypeID int = null,
	@agreementTypeID int = null,
	@activityCode varchar(4)= null,
	@locationID int = null,
	@budgetStartDate datetime = null,
	@budgetEndDate datetime = null,
	@projectStartDate datetime = null,
	@projectEndDate datetime = null,
	@piID int = null,
	@chiefCodeList varchar(1000) = null,
	@sponsorGroupTypeID int = null,
	@budgetEndingDays int = null,
	@projectEndingDays int = null,
	@fundCreatedDays int = null,
	@lowBalance decimal(17,2) = null,
	@highBalance decimal(17,2) = null,
	@agreementStatusTypeList varchar(50)= null,
	@fundStatusTypeID int	= null,
	@categoryID int = null,
	@accountNumber varchar(10) = null,
	@expenseDateFrom datetime = null,
	@expenseDateTo datetime = null,
	@incomingFundNumber varchar(8) = null,
	@monthEndingDate datetime = null
)
as
begin
	set nocount on

	declare @accountID int
	if isnull(@accountNumber,'') = ''
		set @accountID = 0
	else
		set @accountID = (select Id from FinAccount where Number = @accountNumber)

	set @includeProgramProjects = isnull(@includeProgramProjects, 0)
	set @fundNumber = isnull(@fundNumber, '')
	set @folderNumber = isnull(@folderNumber, '')
	set @bicsNumber = isnull(@bicsNumber, '')
	set @walkerNumber = isnull(@walkerNumber, '')
	set @sponsorNumber = isnull(@sponsorNumber, '')
	set @sponsorName = isnull(@sponsorName, '')
	set @sponsorTypeID = isnull(@sponsorTypeID, 0)
	set @agreementTypeID = isnull(@agreementTypeID, 0)
	set @activityCode = isnull(@activityCode, '')
	set @locationID = isnull(@locationID, 0)
	set @budgetStartDate = isnull(@budgetStartDate, '01/01/1900')
	set @budgetEndDate = isnull(@budgetEndDate, '01/01/1900')
	set @projectStartDate = isnull(@projectStartDate, '01/01/1900')
	set @projectEndDate = isnull(@projectEndDate, '01/01/1900')
	set @piID = isnull(@piID, 0)
	set @chiefCodeList = isnull(@chiefCodeList, '')
	set @sponsorGroupTypeID = isnull(@sponsorGroupTypeID, 0)
	set @budgetEndingDays = isnull(@budgetEndingDays, 0)
	set @projectEndingDays = isnull(@projectEndingDays, 0)
	set @fundCreatedDays = isnull(@fundCreatedDays, 0)
	set @lowBalance = isnull(@lowBalance, -922337203685477)
	set @highBalance = isnull(@highBalance, 922337203685477)
	set @agreementStatusTypeList = isnull(@agreementStatusTypeList, '')
	set @fundStatusTypeID = isnull(@fundStatusTypeID, 1)
	set @categoryID = isnull(@categoryID, 0)
	set @accountID = isnull(@accountID, 0)
	set @incomingFundNumber = isnull(@incomingFundNumber, '')
	set @monthEndingDate = isnull(@monthEndingDate, '')

	declare @directCosts int
	set @directCosts = 2

	declare @indirectCosts int
	set @indirectCosts = 3

	declare @revenue int
	set @revenue = 1

	declare @TotalCost int
	set @TotalCost = 4

	declare @CashBalance int
	set @CashBalance = 5

	declare @awardedBudgetTypeId int
	set @awardedBudgetTypeId = 3

	declare @viewFinancialInfoBitValue int
	set @viewFinancialInfoBitValue = 4

	declare @viewPendingAgreementsBitValue int 
	set @viewPendingAgreementsBitValue = 32

	declare @authorizedRightsBitMask int
	set @authorizedRightsBitMask = @viewFinancialInfoBitValue + @viewPendingAgreementsBitValue

	declare @t0 datetime
	set @t0 = current_timestamp

	-- Compute the fund ID based on whether or not the invocation is from an overview or detail context. In the former case,
	-- the @incomingFundNumber is not specified. In the later case, the specified fund number will only be accepted for
	-- further processing only if the specified user has access to that fund.

	declare @fundID int
	if (@incomingFundNumber = '')
		set @fundId = 0
	else
	begin
		select @fundID = [ID] from AgrFund where FundNumber = @incomingFundNumber
		if not exists(select 1 from dbo.CheckFundAccess(@domainUserID, @fundID))
		begin
			declare @message varchar(255)
			set @message = 'User does not have access to fund number ' + @incomingFundNumber
			raiserror(@message, 16, 1)
			return
		end
	end

	-- Generate a list of funds that are accessible to the specified user. When in the detail context, there would only
	-- be one fund to worry about. Since this list of accessible funds is used multiple times, the list is stored in
	-- a table variable.

	create table #accessibleFunds (FundID int primary key, AccessLevel int default 0)

	IF OBJECT_ID('tempdb..#TempFundCollection') is not null drop table #TempFundCollection
	create table #TempFundCollection (FundID int not null, AccessLevel int not null)

	If (@incomingFundNumber = '') begin
		exec GetFundCollection @SessionId, @domainUserID
		Create Unique Index FundId on #TempFundCollection (FundId)
	end
	else
		insert into #TempFundCollection (FundID,AccessLevel) values (@fundID,32767)

	insert into #accessibleFunds
		select * from #TempFundCollection

--	if (@incomingFundNumber = '')
--		insert into #accessibleFunds
--			exec FilterFunds @domainUserID, @authorizedRightsBitMask, @includeProgramProjects,
--				@fundNumber, @folderNumber, @bicsNumber, @walkerNumber, @sponsorNumber, @sponsorName,
--				@sponsorTypeID, @agreementTypeID, @activityCode, @locationID, @budgetStartDate, @budgetEndDate,
--				@projectStartDate, @projectEndDate, @piID, @chiefCodeList, @sponsorGroupTypeID,
--				@budgetEndingDays, @projectEndingDays, @fundCreatedDays, @lowBalance, @highBalance,
--				@agreementStatusTypeList, @fundStatusTypeID
--	else
--		insert into #accessibleFunds (FundID) values (@fundID)

	declare @t1 datetime
	set @t1 = current_timestamp
	print 'Step_1: ' + cast(datediff(ss, @t0, @t1) as varchar)

	-- The expense date range should be from the first day of the 'from' month/year to the last day of the 'to' month/year.
	-- The 'to' date is clamped to the first day of the current month/year.
	-- There are three scenairos to handle:
	-- 1. Both dates are specified
	-- 2. Neither dates are specified
	-- 3. One of the dates is specified
	-- 3a. If the 'from' date is specified, the 'to' date is the mininum of the last gl close date and the 'from' + 12 months
	-- 3b. If the 'to' date is specified, the 'from' date is 'to' - 12 months

	Declare @refreshDatesTable table (glPostAsOfDate datetime,salaryAsOfDate datetime, poapAsOfDate datetime)

	Insert into @refreshDatesTable Exec GetRefreshDates

	Declare @glPostAsOfDate DateTime
	select @glPostAsOfDate = glPostAsOfDate from @refreshDatesTable

	if ((@expenseDateTo is null) or (@expenseDateTo > @glPostAsOfDate))
		set @expenseDateTo = @glPostAsOfDate

	if (@expenseDateFrom is null)
		set @expenseDateFrom = '01/01/1900'		--dateadd(day, 1, dateadd(month, -12, @expenseDateTo))
	else
		set @expenseDateFrom = dateadd(day, -datepart(day, @expenseDateFrom) + 1, @expenseDateFrom)

	-- Retrieve the list of month-end dates between the from and to date range. This is saved in a table variable
	-- for later reuse.
	create table #dateRange ([ID] int primary key identity(1, 1), MonthEndingDate datetime)

	insert into #dateRange
		select Dates from dbo.GetDateRanges(@expenseDateFrom, @expenseDateTo)

	declare @t2 datetime
	set @t2 = current_timestamp
	print 'Step_2: ' + cast(datediff(ss, @t1, @t2) as varchar)

--start
	declare  @FinAccts table (CategoryID int, CategoryName varchar(50), 
		AccountID int, AccountNumber varchar(50), SortOrder int)

	insert into  @FinAccts
	select distinct fc.[ID],
			fc.[Name],
			fa.[ID],
			fa.Number + ' - ' + [Description],
			fc.SortOrder
	from 
		FinAccount fa 
		inner join FinCategory fc on fc.[ID] = fa.FinCategoryID

	where fc.[Name] not in ('INDIRECT COSTS', 'INVESTMENT INCOME', 'OTHER INCOME')
	and (fc.[ID] = @categoryID or @categoryID = 0) 
	and (fa.ID = @accountID or @accountID = 0)


	if @expenseDateFrom = '1900-01-01 00:00:00'
	begin
		declare @firstMonthWithExpenses datetime
		set @firstMonthWithExpenses = (
			select top 1 MonthEndingDate  
				from MonthlyFundAccountActuals mfaa
				inner join @FinAccts fa on mfaa.AccountID = fa.AccountID
				inner join #accessibleFunds af on mfaa.FundID = af.FundID 
				where mfaa.Amount <> 0
				order by MonthEndingDate Asc)

		delete	#dateRange
		where	MonthEndingDate < @firstMonthWithExpenses
		set @expenseDateFrom = @firstMonthWithExpenses
	end
--	-- The fourth table in the resultset contains account information for each expense month.
-- Fourth result set


	select 
		fa.AccountID,
		fa.AccountNumber,
		fa.CategoryID,
		fa.CategoryName,
		fa.SortOrder,
		convert(DateTime, mfaa.MonthEndingDate, 101) as ExpenseMonth,
		IsNull(Sum(mfaa.Amount),0) as ExpenseAmount
		from @finaccts fa
		join MonthlyFundAccountActuals mfaa on mfaa.AccountID = fa.AccountID
		join #accessibleFunds af on mfaa.FundID = af.FundID
		join #dateRange dr on mfaa.MonthEndingDate = dr.MonthEndingDate
		group by
			fa.SortOrder, fa.AccountID, fa.AccountNumber, fa.CategoryID, fa.CategoryName, mfaa.MonthEndingDate
		order by
			fa.SortOrder, fa.AccountID, fa.CategoryID, mfaa.MonthEndingDate

	drop table #dateRange
	drop table #accessibleFunds
end








GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Creating [dbo].[GetExpenseInfo_FundCount]'
GO


CREATE procedure [dbo].[GetExpenseInfo_FundCount]
(   @SessionID varchar(100),
	@domainUserID int,
	@includeProgramProjects bit = null,
	@fundNumber varchar(8) = null,
	@folderNumber varchar(16) = null,
	@bicsNumber varchar(10) = null,
	@walkerNumber varchar(10) = null,
	@sponsorNumber varchar(32) = null,
	@sponsorName varchar(64) = null,
	@sponsorTypeID int = null,
	@agreementTypeID int = null,
	@activityCode varchar(4)= null,
	@locationID int = null,
	@budgetStartDate datetime = null,
	@budgetEndDate datetime = null,
	@projectStartDate datetime = null,
	@projectEndDate datetime = null,
	@piID int = null,
	@chiefCodeList varchar(1000) = null,
	@sponsorGroupTypeID int = null,
	@budgetEndingDays int = null,
	@projectEndingDays int = null,
	@fundCreatedDays int = null,
	@lowBalance decimal(17,2) = null,
	@highBalance decimal(17,2) = null,
	@agreementStatusTypeList varchar(50)= null,
	@fundStatusTypeID int	= null,
	@categoryID int = null,
	@accountNumber varchar(10) = null,
	@expenseDateFrom datetime = null,
	@expenseDateTo datetime = null,
	@incomingFundNumber varchar(8) = null,
	@monthEndingDate datetime = null
)
as

begin
	set nocount on

	declare @accountID int
	if isnull(@accountNumber,'') = ''
		set @accountID = 0
	else
		set @accountID = (select Id from FinAccount where Number = @accountNumber)

	set @includeProgramProjects = isnull(@includeProgramProjects, 0)
	set @fundNumber = isnull(@fundNumber, '')
	set @folderNumber = isnull(@folderNumber, '')
	set @bicsNumber = isnull(@bicsNumber, '')
	set @walkerNumber = isnull(@walkerNumber, '')
	set @sponsorNumber = isnull(@sponsorNumber, '')
	set @sponsorName = isnull(@sponsorName, '')
	set @sponsorTypeID = isnull(@sponsorTypeID, 0)
	set @agreementTypeID = isnull(@agreementTypeID, 0)
	set @activityCode = isnull(@activityCode, '')
	set @locationID = isnull(@locationID, 0)
	set @budgetStartDate = isnull(@budgetStartDate, '01/01/1900')
	set @budgetEndDate = isnull(@budgetEndDate, '01/01/1900')
	set @projectStartDate = isnull(@projectStartDate, '01/01/1900')
	set @projectEndDate = isnull(@projectEndDate, '01/01/1900')
	set @piID = isnull(@piID, 0)
	set @chiefCodeList = isnull(@chiefCodeList, '')
	set @sponsorGroupTypeID = isnull(@sponsorGroupTypeID, 0)
	set @budgetEndingDays = isnull(@budgetEndingDays, 0)
	set @projectEndingDays = isnull(@projectEndingDays, 0)
	set @fundCreatedDays = isnull(@fundCreatedDays, 0)
	set @lowBalance = isnull(@lowBalance, -922337203685477)
	set @highBalance = isnull(@highBalance, 922337203685477)
	set @agreementStatusTypeList = isnull(@agreementStatusTypeList, '')
	set @fundStatusTypeID = isnull(@fundStatusTypeID, 1)
	set @categoryID = isnull(@categoryID, 0)
	set @accountID = isnull(@accountID, 0)
	set @incomingFundNumber = isnull(@incomingFundNumber, '')
	set @monthEndingDate = isnull(@monthEndingDate, '')

	declare @directCosts int
	set @directCosts = 2

	declare @indirectCosts int
	set @indirectCosts = 3

	declare @revenue int
	set @revenue = 1

	declare @TotalCost int
	set @TotalCost = 4

	declare @CashBalance int
	set @CashBalance = 5

	declare @awardedBudgetTypeId int
	set @awardedBudgetTypeId = 3

	declare @viewFinancialInfoBitValue int
	set @viewFinancialInfoBitValue = 4

	declare @viewPendingAgreementsBitValue int 
	set @viewPendingAgreementsBitValue = 32

	declare @authorizedRightsBitMask int
	set @authorizedRightsBitMask = @viewFinancialInfoBitValue + @viewPendingAgreementsBitValue

	declare @t0 datetime
	set @t0 = current_timestamp

	-- Compute the fund ID based on whether or not the invocation is from an overview or detail context. In the former case,
	-- the @incomingFundNumber is not specified. In the later case, the specified fund number will only be accepted for
	-- further processing only if the specified user has access to that fund.

	declare @fundID int
	if (@incomingFundNumber = '')
		set @fundId = 0
	else
	begin
		select @fundID = [ID] from AgrFund where FundNumber = @incomingFundNumber
		if not exists(select 1 from dbo.CheckFundAccess(@domainUserID, @fundID))
		begin
			declare @message varchar(255)
			set @message = 'User does not have access to fund number ' + @incomingFundNumber
			raiserror(@message, 16, 1)
			return
		end
	end

	-- Generate a list of funds that are accessible to the specified user. When in the detail context, there would only
	-- be one fund to worry about. Since this list of accessible funds is used multiple times, the list is stored in
	-- a table variable.

	create table #accessibleFunds (FundID int primary key, AccessLevel int default 0)

	IF OBJECT_ID('tempdb..#TempFundCollection') is not null drop table #TempFundCollection
	create table #TempFundCollection (FundID int not null, AccessLevel int not null)

	If (@incomingFundNumber = '') begin
		exec GetFundCollection @SessionId, @domainUserID
		Create Unique Index FundId on #TempFundCollection (FundId)
	end
	else
		insert into #TempFundCollection (FundID,AccessLevel) values (@fundID,32767)

	insert into #accessibleFunds
		select * from #TempFundCollection

--	if (@incomingFundNumber = '')
--		insert into #accessibleFunds
--			exec FilterFunds @domainUserID, @authorizedRightsBitMask, @includeProgramProjects,
--				@fundNumber, @folderNumber, @bicsNumber, @walkerNumber, @sponsorNumber, @sponsorName,
--				@sponsorTypeID, @agreementTypeID, @activityCode, @locationID, @budgetStartDate, @budgetEndDate,
--				@projectStartDate, @projectEndDate, @piID, @chiefCodeList, @sponsorGroupTypeID,
--				@budgetEndingDays, @projectEndingDays, @fundCreatedDays, @lowBalance, @highBalance,
--				@agreementStatusTypeList, @fundStatusTypeID
--	else
--		insert into #accessibleFunds (FundID) values (@fundID)

	declare @t1 datetime
	set @t1 = current_timestamp
	print 'Step_1: ' + cast(datediff(ss, @t0, @t1) as varchar)

	-- The expense date range should be from the first day of the 'from' month/year to the last day of the 'to' month/year.
	-- The 'to' date is clamped to the first day of the current month/year.
	-- There are three scenairos to handle:
	-- 1. Both dates are specified
	-- 2. Neither dates are specified
	-- 3. One of the dates is specified
	-- 3a. If the 'from' date is specified, the 'to' date is the mininum of the last gl close date and the 'from' + 12 months
	-- 3b. If the 'to' date is specified, the 'from' date is 'to' - 12 months

	Declare @refreshDatesTable table (glPostAsOfDate datetime,salaryAsOfDate datetime, poapAsOfDate datetime)

	Insert into @refreshDatesTable Exec GetRefreshDates

	Declare @glPostAsOfDate DateTime
	select @glPostAsOfDate = glPostAsOfDate from @refreshDatesTable

	if ((@expenseDateTo is null) or (@expenseDateTo > @glPostAsOfDate))
		set @expenseDateTo = @glPostAsOfDate

	if (@expenseDateFrom is null)
		set @expenseDateFrom = '01/01/1900'		--dateadd(day, 1, dateadd(month, -12, @expenseDateTo))
	else
		set @expenseDateFrom = dateadd(day, -datepart(day, @expenseDateFrom) + 1, @expenseDateFrom)

	-- Retrieve the list of month-end dates between the from and to date range. This is saved in a table variable
	-- for later reuse.
	create table #dateRange ([ID] int primary key identity(1, 1), MonthEndingDate datetime)

	insert into #dateRange
		select Dates from dbo.GetDateRanges(@expenseDateFrom, @expenseDateTo)

	declare @t2 datetime
	set @t2 = current_timestamp
	print 'Step_2: ' + cast(datediff(ss, @t1, @t2) as varchar)

--start
	declare  @FinAccts table (CategoryID int, CategoryName varchar(50), 
		AccountID int, AccountNumber varchar(50), SortOrder int)

	insert into  @FinAccts
	select distinct fc.[ID],
			fc.[Name],
			fa.[ID],
			fa.Number + ' - ' + [Description],
			fc.SortOrder
	from 
		FinAccount fa 
		inner join FinCategory fc on fc.[ID] = fa.FinCategoryID
--		inner join MonthlyFundAccountActuals mfaa on mfaa.AccountID = fa.id
--		inner join #accessibleFunds af on mfaa.FundID = af.FundID 
--		inner join #dateRange dr on mfaa.MonthEndingDate = dr.MonthEndingDate

	where fc.[Name] not in ('INDIRECT COSTS', 'INVESTMENT INCOME', 'OTHER INCOME')
	and (fc.[ID] = @categoryID or @categoryID = 0) 
	and (fa.ID = @accountID or @accountID = 0)


	if @expenseDateFrom = '1900-01-01 00:00:00'
	begin
		declare @firstMonthWithExpenses datetime
		set @firstMonthWithExpenses = (
			select top 1 MonthEndingDate  
				from MonthlyFundAccountActuals mfaa
				inner join @FinAccts fa on mfaa.AccountID = fa.AccountID
				inner join #accessibleFunds af on mfaa.FundID = af.FundID 
				where mfaa.Amount <> 0
				order by MonthEndingDate Asc)

		delete	#dateRange
		where	MonthEndingDate < @firstMonthWithExpenses
		set @expenseDateFrom = @firstMonthWithExpenses
	end


	declare @t3 datetime
	set @t3 = current_timestamp
	print 'Step_3: ' + cast(datediff(ss, @t2, @t3) as varchar)

	select
		count(distinct mfaa.FundID) as FundCount,
		convert(varchar(10), dr.MonthEndingDate, 101) as ExpenseMonth
		from 
			MonthlyFundAccountActuals mfaa
			inner join @FinAccts fa on mfaa.AccountID = fa.AccountID
			inner join #accessibleFunds af on mfaa.FundID = af.FundID
			right outer join #dateRange dr on mfaa.MonthEndingDate = dr.MonthEndingDate 
		group by
			dr.MonthEndingDate
		order by
			dr.MonthEndingDate asc

end

GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Creating [dbo].[GetExpenseInfo_Account_Category_Month]'
GO




CREATE procedure [dbo].[GetExpenseInfo_Account_Category_Month]
(   @SessionID varchar(100),
	@domainUserID int,
	@includeProgramProjects bit = null,
	@fundNumber varchar(8) = null,
	@folderNumber varchar(16) = null,
	@bicsNumber varchar(10) = null,
	@walkerNumber varchar(10) = null,
	@sponsorNumber varchar(32) = null,
	@sponsorName varchar(64) = null,
	@sponsorTypeID int = null,
	@agreementTypeID int = null,
	@activityCode varchar(4)= null,
	@locationID int = null,
	@budgetStartDate datetime = null,
	@budgetEndDate datetime = null,
	@projectStartDate datetime = null,
	@projectEndDate datetime = null,
	@piID int = null,
	@chiefCodeList varchar(1000) = null,
	@sponsorGroupTypeID int = null,
	@budgetEndingDays int = null,
	@projectEndingDays int = null,
	@fundCreatedDays int = null,
	@lowBalance decimal(17,2) = null,
	@highBalance decimal(17,2) = null,
	@agreementStatusTypeList varchar(50)= null,
	@fundStatusTypeID int	= null,
	@categoryID int = null,
	@accountNumber varchar(10) = null,
	@expenseDateFrom datetime = null,
	@expenseDateTo datetime = null,
	@incomingFundNumber varchar(8) = null,
	@monthEndingDate datetime = null
)
as
begin
	set nocount on

	declare @accountID int
	if isnull(@accountNumber,'') = ''
		set @accountID = 0
	else
		set @accountID = (select Id from FinAccount where Number = @accountNumber)

	set @includeProgramProjects = isnull(@includeProgramProjects, 0)
	set @fundNumber = isnull(@fundNumber, '')
	set @folderNumber = isnull(@folderNumber, '')
	set @bicsNumber = isnull(@bicsNumber, '')
	set @walkerNumber = isnull(@walkerNumber, '')
	set @sponsorNumber = isnull(@sponsorNumber, '')
	set @sponsorName = isnull(@sponsorName, '')
	set @sponsorTypeID = isnull(@sponsorTypeID, 0)
	set @agreementTypeID = isnull(@agreementTypeID, 0)
	set @activityCode = isnull(@activityCode, '')
	set @locationID = isnull(@locationID, 0)
	set @budgetStartDate = isnull(@budgetStartDate, '01/01/1900')
	set @budgetEndDate = isnull(@budgetEndDate, '01/01/1900')
	set @projectStartDate = isnull(@projectStartDate, '01/01/1900')
	set @projectEndDate = isnull(@projectEndDate, '01/01/1900')
	set @piID = isnull(@piID, 0)
	set @chiefCodeList = isnull(@chiefCodeList, '')
	set @sponsorGroupTypeID = isnull(@sponsorGroupTypeID, 0)
	set @budgetEndingDays = isnull(@budgetEndingDays, 0)
	set @projectEndingDays = isnull(@projectEndingDays, 0)
	set @fundCreatedDays = isnull(@fundCreatedDays, 0)
	set @lowBalance = isnull(@lowBalance, -922337203685477)
	set @highBalance = isnull(@highBalance, 922337203685477)
	set @agreementStatusTypeList = isnull(@agreementStatusTypeList, '')
	set @fundStatusTypeID = isnull(@fundStatusTypeID, 1)
	set @categoryID = isnull(@categoryID, 0)
	set @accountID = isnull(@accountID, 0)
	set @incomingFundNumber = isnull(@incomingFundNumber, '')
	set @monthEndingDate = isnull(@monthEndingDate, '')

	declare @directCosts int
	set @directCosts = 2

	declare @indirectCosts int
	set @indirectCosts = 3

	declare @revenue int
	set @revenue = 1

	declare @TotalCost int
	set @TotalCost = 4

	declare @CashBalance int
	set @CashBalance = 5

	declare @awardedBudgetTypeId int
	set @awardedBudgetTypeId = 3

	declare @viewFinancialInfoBitValue int
	set @viewFinancialInfoBitValue = 4

	declare @viewPendingAgreementsBitValue int 
	set @viewPendingAgreementsBitValue = 32

	declare @authorizedRightsBitMask int
	set @authorizedRightsBitMask = @viewFinancialInfoBitValue + @viewPendingAgreementsBitValue

	declare @t0 datetime
	set @t0 = current_timestamp

	-- Compute the fund ID based on whether or not the invocation is from an overview or detail context. In the former case,
	-- the @incomingFundNumber is not specified. In the later case, the specified fund number will only be accepted for
	-- further processing only if the specified user has access to that fund.

	declare @fundID int
	if (@incomingFundNumber = '')
		set @fundId = 0
	else
	begin
		select @fundID = [ID] from AgrFund where FundNumber = @incomingFundNumber
		if not exists(select 1 from dbo.CheckFundAccess(@domainUserID, @fundID))
		begin
			declare @message varchar(255)
			set @message = 'User does not have access to fund number ' + @incomingFundNumber
			raiserror(@message, 16, 1)
			return
		end
	end

	-- Generate a list of funds that are accessible to the specified user. When in the detail context, there would only
	-- be one fund to worry about. Since this list of accessible funds is used multiple times, the list is stored in
	-- a table variable.

	create table #accessibleFunds (FundID int primary key, AccessLevel int default 0)

	IF OBJECT_ID('tempdb..#TempFundCollection') is not null drop table #TempFundCollection
	create table #TempFundCollection (FundID int not null, AccessLevel int not null)

	If (@incomingFundNumber = '') begin
		exec GetFundCollection @SessionId, @domainUserID
		Create Unique Index FundId on #TempFundCollection (FundId)
	end
	else
		insert into #TempFundCollection (FundID,AccessLevel) values (@fundID,32767)

	insert into #accessibleFunds
		select * from #TempFundCollection

--	if (@incomingFundNumber = '')
--		insert into #accessibleFunds
--			exec FilterFunds @domainUserID, @authorizedRightsBitMask, @includeProgramProjects,
--				@fundNumber, @folderNumber, @bicsNumber, @walkerNumber, @sponsorNumber, @sponsorName,
--				@sponsorTypeID, @agreementTypeID, @activityCode, @locationID, @budgetStartDate, @budgetEndDate,
--				@projectStartDate, @projectEndDate, @piID, @chiefCodeList, @sponsorGroupTypeID,
--				@budgetEndingDays, @projectEndingDays, @fundCreatedDays, @lowBalance, @highBalance,
--				@agreementStatusTypeList, @fundStatusTypeID
--	else
--		insert into #accessibleFunds (FundID) values (@fundID)

	declare @t1 datetime
	set @t1 = current_timestamp
	print 'Step_1: ' + cast(datediff(ss, @t0, @t1) as varchar)

	-- The expense date range should be from the first day of the 'from' month/year to the last day of the 'to' month/year.
	-- The 'to' date is clamped to the first day of the current month/year.
	-- There are three scenairos to handle:
	-- 1. Both dates are specified
	-- 2. Neither dates are specified
	-- 3. One of the dates is specified
	-- 3a. If the 'from' date is specified, the 'to' date is the mininum of the last gl close date and the 'from' + 12 months
	-- 3b. If the 'to' date is specified, the 'from' date is 'to' - 12 months

	Declare @refreshDatesTable table (glPostAsOfDate datetime,salaryAsOfDate datetime, poapAsOfDate datetime)

	Insert into @refreshDatesTable Exec GetRefreshDates

	Declare @glPostAsOfDate DateTime
	select @glPostAsOfDate = glPostAsOfDate from @refreshDatesTable

	if ((@expenseDateTo is null) or (@expenseDateTo > @glPostAsOfDate))
		set @expenseDateTo = @glPostAsOfDate

	if (@expenseDateFrom is null)
		set @expenseDateFrom = '01/01/1900'		--dateadd(day, 1, dateadd(month, -12, @expenseDateTo))
	else
		set @expenseDateFrom = dateadd(day, -datepart(day, @expenseDateFrom) + 1, @expenseDateFrom)

	-- Retrieve the list of month-end dates between the from and to date range. This is saved in a table variable
	-- for later reuse.
	create table #dateRange ([ID] int primary key identity(1, 1), MonthEndingDate datetime)

	insert into #dateRange
		select Dates from dbo.GetDateRanges(@expenseDateFrom, @expenseDateTo)

	declare @t2 datetime
	set @t2 = current_timestamp
	print 'Step_2: ' + cast(datediff(ss, @t1, @t2) as varchar)

--start
	declare  @FinAccts table (CategoryID int, CategoryName varchar(50), 
		AccountID int, AccountNumber varchar(50), SortOrder int)

	insert into  @FinAccts
	select distinct fc.[ID],
			fc.[Name],
			fa.[ID],
			fa.Number + ' - ' + [Description],
			fc.SortOrder
	from 
		FinAccount fa 
		inner join FinCategory fc on fc.[ID] = fa.FinCategoryID

	where fc.[Name] not in ('INDIRECT COSTS', 'INVESTMENT INCOME', 'OTHER INCOME')
	and (fc.[ID] = @categoryID or @categoryID = 0) 
	and (fa.ID = @accountID or @accountID = 0)


	if @expenseDateFrom = '1900-01-01 00:00:00'
	begin
		declare @firstMonthWithExpenses datetime
		set @firstMonthWithExpenses = (
			select top 1 MonthEndingDate  
				from MonthlyFundAccountActuals mfaa
				inner join @FinAccts fa on mfaa.AccountID = fa.AccountID
				inner join #accessibleFunds af on mfaa.FundID = af.FundID 
				where mfaa.Amount <> 0
				order by MonthEndingDate Asc)

		delete	#dateRange
		where	MonthEndingDate < @firstMonthWithExpenses
		set @expenseDateFrom = @firstMonthWithExpenses
	end
--	-- The fourth table in the resultset contains account information for each expense month.
-- Fourth result set

	declare @AcctCatDate table (AccountID int, AccountNumber varchar(50), CategoryID int, CategoryName varchar(50), SortOrder int)

	insert into @AcctCatDate
	select distinct fa.AccountID, fa.AccountNumber, CategoryID,  CategoryName, SortOrder 
	from @finaccts fa
	join MonthlyFundAccountActuals mfaa on mfaa.AccountID = fa.AccountID
	join #accessibleFunds af on mfaa.FundID = af.FundID
	
	select 
		ct.AccountID,
		ct.AccountNumber,
		ct.CategoryID,
		ct.CategoryName,
		ct.SortOrder,
		convert(DateTime, ct.MonthEndingDate, 101) as ExpenseMonth,
		IsNull(Sum(mfaa.Amount),0) as ExpenseAmount
		from 
			MonthlyFundAccountActuals mfaa
			join #accessibleFunds af on mfaa.FundID = af.FundID
			join #dateRange dr on mfaa.MonthEndingDate = dr.MonthEndingDate
			right join
				(
				select * from @AcctCatDate cross join #DateRange
				) ct on mfaa.AccountID = ct.AccountID and ct.MonthEndingDate = mfaa.MonthEndingDate
		group by
			ct.SortOrder, ct.AccountID, ct.AccountNumber, ct.CategoryID, ct.CategoryName, ct.MonthEndingDate
		order by
			ct.SortOrder, ct.AccountID, ct.CategoryID, ct.MonthEndingDate

	drop table #dateRange
	drop table #accessibleFunds
end









GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Altering [dbo].[GetProtocolActivityList]'
GO

ALTER PROCEDURE dbo.GetProtocolActivityList
(
	@UserName varchar(20),
	@DomainUserId int,
	@protocolNumber  VARCHAR(12)=null,
	@protocolTitle VARCHAR(1024)=null
)
AS

	DECLARE @protocolresourcetypeid varchar(2)
	DECLARE @hourDiff int

	set @protocolresourcetypeid = (select [id] from FwkResourceType where [Name] = 'Protocol')
	set @hourDiff = (select datediff(hour, getdate(), getutcdate())) * -1

	select 
		P.[ID] as ProtocolID,
		P.ProtocolNumber as ProtocolNumber, 
		P.Title as ProtocolTitle, 
		ADMPI.FirstName + ' ' + ADMPI.LastName as PIName, 
		PP.[ID] as ProtocolProcessID,
		rfc.RefMeaning as Type,
		PP.Type as TypeCode,
		PP.Type, 
		SWAL.ActionRequired as NeededAction,
		DATEADD(hh,@hourDiff,SWAL.AssignedOn) as DateAssigned,
		isnull(arl.AccessLevel,64) as AccessLevel,
		PPWF.ExecutionId
	from 		
		dbo.Protocol P
	 		
		LEFT JOIN dbo.fnAdmQGetAuthorizedResourceList(@DomainUserId, @protocolresourcetypeid) arl
		on arl.resourceid = p.fwkresourceid 
		
		INNER JOIN dbo.protocolProcess pp 
		ON p.[Id] = pp.ProtocolId

		INNER JOIN dbo.ADMPerson ADMPI 
		ON P.PIPersonID = ADMPI.[Id]

		INNER JOIN dbo.ProtocolProcess_WorkFlow_Map PPWF
		ON PP.[ID] = PPWF.ProtocolProcessID

		INNER JOIN dbo.SWActivityList SWAL
		ON PPWF.ExecutionID = SWAL.ExecutionID

		INNER JOIN dbo.SWVirtualUser SWVU
		ON SWAL.VirtualUserID = SWVU.[ID]
		
		INNER JOIN dbo.ADMPerson ADMP
		ON SWVU.UserID = ADMP.[FWKDomainuserid]

		INNER JOIN FWKDomainUser FDU		
		ON ADMP.[FWKDomainuserid] = FDU.[Id]		
		
		INNER JOIN RefCode rfc 
		ON rfc.[RefCode] = pp.Type
	where					
		ISNULL(CAST(p.ProtocolNumber AS VARCHAR(12)),'*')like ISNULL(CAST(@protocolNumber AS VARCHAR(12)), '%')
		and ISNULL(CAST(p.Title AS VARCHAR(1024)),'*')like ISNULL(CAST(@protocolTitle AS VARCHAR(1024)) + '%', '%')
		and FDU.UserName = @UserName	
		and SWAL.Status = 'awaiting'
		and P.Markfordeletion = 0
	Order by p.ProtocolNumber DESC ,p.Title ASC



GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Creating [dbo].[GetExpenseInfo_FinType_Month_Geo]'
GO







CREATE procedure [dbo].[GetExpenseInfo_FinType_Month_Geo]
(   @SessionID varchar(100),
	@domainUserID int,
	@includeProgramProjects bit = null,
	@fundNumber varchar(8) = null,
	@folderNumber varchar(16) = null,
	@bicsNumber varchar(10) = null,
	@walkerNumber varchar(10) = null,
	@sponsorNumber varchar(32) = null,
	@sponsorName varchar(64) = null,
	@sponsorTypeID int = null,
	@agreementTypeID int = null,
	@activityCode varchar(4)= null,
	@locationID int = null,
	@budgetStartDate datetime = null,
	@budgetEndDate datetime = null,
	@projectStartDate datetime = null,
	@projectEndDate datetime = null,
	@piID int = null,
	@chiefCodeList varchar(1000) = null,
	@sponsorGroupTypeID int = null,
	@budgetEndingDays int = null,
	@projectEndingDays int = null,
	@fundCreatedDays int = null,
	@lowBalance decimal(17,2) = null,
	@highBalance decimal(17,2) = null,
	@agreementStatusTypeList varchar(50)= null,
	@fundStatusTypeID int	= null,
	@categoryID int = null,
	@accountNumber varchar(10) = null,
	@expenseDateFrom datetime = null,
	@expenseDateTo datetime = null,
	@incomingFundNumber varchar(8) = null,
	@monthEndingDate datetime = null
)
as
begin
	set nocount on

	declare @accountID int
	if isnull(@accountNumber,'') = ''
		set @accountID = 0
	else
		set @accountID = (select Id from FinAccount where Number = @accountNumber)

	set @includeProgramProjects = isnull(@includeProgramProjects, 0)
	set @fundNumber = isnull(@fundNumber, '')
	set @folderNumber = isnull(@folderNumber, '')
	set @bicsNumber = isnull(@bicsNumber, '')
	set @walkerNumber = isnull(@walkerNumber, '')
	set @sponsorNumber = isnull(@sponsorNumber, '')
	set @sponsorName = isnull(@sponsorName, '')
	set @sponsorTypeID = isnull(@sponsorTypeID, 0)
	set @agreementTypeID = isnull(@agreementTypeID, 0)
	set @activityCode = isnull(@activityCode, '')
	set @locationID = isnull(@locationID, 0)
	set @budgetStartDate = isnull(@budgetStartDate, '01/01/1900')
	set @budgetEndDate = isnull(@budgetEndDate, '01/01/1900')
	set @projectStartDate = isnull(@projectStartDate, '01/01/1900')
	set @projectEndDate = isnull(@projectEndDate, '01/01/1900')
	set @piID = isnull(@piID, 0)
	set @chiefCodeList = isnull(@chiefCodeList, '')
	set @sponsorGroupTypeID = isnull(@sponsorGroupTypeID, 0)
	set @budgetEndingDays = isnull(@budgetEndingDays, 0)
	set @projectEndingDays = isnull(@projectEndingDays, 0)
	set @fundCreatedDays = isnull(@fundCreatedDays, 0)
	set @lowBalance = isnull(@lowBalance, -922337203685477)
	set @highBalance = isnull(@highBalance, 922337203685477)
	set @agreementStatusTypeList = isnull(@agreementStatusTypeList, '')
	set @fundStatusTypeID = isnull(@fundStatusTypeID, 1)
	set @categoryID = isnull(@categoryID, 0)
	set @accountID = isnull(@accountID, 0)
	set @incomingFundNumber = isnull(@incomingFundNumber, '')
	set @monthEndingDate = isnull(@monthEndingDate, '')

	declare @directCosts int
	set @directCosts = 2

	declare @indirectCosts int
	set @indirectCosts = 3

	declare @revenue int
	set @revenue = 1

	declare @TotalCost int
	set @TotalCost = 4

	declare @CashBalance int
	set @CashBalance = 5

	declare @awardedBudgetTypeId int
	set @awardedBudgetTypeId = 3

	declare @viewFinancialInfoBitValue int
	set @viewFinancialInfoBitValue = 4

	declare @viewPendingAgreementsBitValue int 
	set @viewPendingAgreementsBitValue = 32

	declare @authorizedRightsBitMask int
	set @authorizedRightsBitMask = @viewFinancialInfoBitValue + @viewPendingAgreementsBitValue

	declare @t0 datetime
	set @t0 = current_timestamp

	-- Compute the fund ID based on whether or not the invocation is from an overview or detail context. In the former case,
	-- the @incomingFundNumber is not specified. In the later case, the specified fund number will only be accepted for
	-- further processing only if the specified user has access to that fund.

	declare @fundID int
	if (@incomingFundNumber = '')
		set @fundId = 0
	else
	begin
		select @fundID = [ID] from AgrFund where FundNumber = @incomingFundNumber
		if not exists(select 1 from dbo.CheckFundAccess(@domainUserID, @fundID))
		begin
			declare @message varchar(255)
			set @message = 'User does not have access to fund number ' + @incomingFundNumber
			raiserror(@message, 16, 1)
			return
		end
	end

	-- Generate a list of funds that are accessible to the specified user. When in the detail context, there would only
	-- be one fund to worry about. Since this list of accessible funds is used multiple times, the list is stored in
	-- a table variable.

	create table #accessibleFunds (FundID int primary key, AccessLevel int default 0)

	IF OBJECT_ID('tempdb..#TempFundCollection') is not null drop table #TempFundCollection
	create table #TempFundCollection (FundID int not null, AccessLevel int not null)

	If (@incomingFundNumber = '') begin
		exec GetFundCollection @SessionId, @domainUserID
		Create Unique Index FundId on #TempFundCollection (FundId)
	end
	else
		insert into #TempFundCollection (FundID,AccessLevel) values (@fundID,32767)

	insert into #accessibleFunds
		select * from #TempFundCollection
--	create table ##accessibleFunds (FundID int primary key, AccessLevel int default 0)
--	insert into ##accessibleFunds
--		select * from #TempFundCollection


--	if (@incomingFundNumber = '')
--		insert into #accessibleFunds
--			exec FilterFunds @domainUserID, @authorizedRightsBitMask, @includeProgramProjects,
--				@fundNumber, @folderNumber, @bicsNumber, @walkerNumber, @sponsorNumber, @sponsorName,
--				@sponsorTypeID, @agreementTypeID, @activityCode, @locationID, @budgetStartDate, @budgetEndDate,
--				@projectStartDate, @projectEndDate, @piID, @chiefCodeList, @sponsorGroupTypeID,
--				@budgetEndingDays, @projectEndingDays, @fundCreatedDays, @lowBalance, @highBalance,
--				@agreementStatusTypeList, @fundStatusTypeID
--	else
--		insert into #accessibleFunds (FundID) values (@fundID)

	declare @t1 datetime
	set @t1 = current_timestamp
	print 'Step_1: ' + cast(datediff(ss, @t0, @t1) as varchar)

	-- The expense date range should be from the first day of the 'from' month/year to the last day of the 'to' month/year.
	-- The 'to' date is clamped to the first day of the current month/year.
	-- There are three scenairos to handle:
	-- 1. Both dates are specified
	-- 2. Neither dates are specified
	-- 3. One of the dates is specified
	-- 3a. If the 'from' date is specified, the 'to' date is the mininum of the last gl close date and the 'from' + 12 months
	-- 3b. If the 'to' date is specified, the 'from' date is 'to' - 12 months

	Declare @refreshDatesTable table (glPostAsOfDate datetime,salaryAsOfDate datetime, poapAsOfDate datetime)

	Insert into @refreshDatesTable Exec GetRefreshDates

	Declare @glPostAsOfDate DateTime
	select @glPostAsOfDate = glPostAsOfDate from @refreshDatesTable

	if ((@expenseDateTo is null) or (@expenseDateTo > @glPostAsOfDate))
		set @expenseDateTo = @glPostAsOfDate

	if (@expenseDateFrom is null)
		set @expenseDateFrom = '01/01/1900'		--dateadd(day, 1, dateadd(month, -12, @expenseDateTo))
	else
		set @expenseDateFrom = dateadd(day, -datepart(day, @expenseDateFrom) + 1, @expenseDateFrom)

	-- Retrieve the list of month-end dates between the from and to date range. This is saved in a table variable
	-- for later reuse.
	create table #dateRange ([ID] int primary key identity(1, 1), MonthEndingDate datetime)

	insert into #dateRange
		select Dates from dbo.GetDateRanges(@expenseDateFrom, @expenseDateTo)

	declare @t2 datetime
	set @t2 = current_timestamp
	print 'Step_2: ' + cast(datediff(ss, @t1, @t2) as varchar)

--start
	declare  @FinAccts table (CategoryID int, CategoryName varchar(50), 
		AccountID int, AccountNumber varchar(50), SortOrder int)

	insert into  @FinAccts
	select distinct fc.[ID],
			fc.[Name],
			fa.[ID],
			fa.Number + ' - ' + [Description],
			fc.SortOrder
	from 
		FinAccount fa 
		inner join FinCategory fc on fc.[ID] = fa.FinCategoryID
		INNER join MonthlyFundAccountActuals mfaa on mfaa.AccountID = fa.ID
		Inner join #accessibleFunds af on mfaa.FundID = af.FundID
		Inner join #DateRange dr on mfaa.MonthEndingDate = dr.MonthEndingDate
	where fc.[Name] not in ('INDIRECT COSTS', 'INVESTMENT INCOME', 'OTHER INCOME')
	and (fc.[ID] = @categoryID or @categoryID = 0) 
	and (fa.ID = @accountID or @accountID = 0)


	if @expenseDateFrom = '1900-01-01 00:00:00'
	begin
		declare @firstMonthWithExpenses datetime
		set @firstMonthWithExpenses = (
			select Min( mfaa.MonthEndingDate )
				from MonthlyFundAccountActuals mfaa
				inner join @FinAccts fa on mfaa.AccountID = fa.AccountID
				inner join #accessibleFunds af on mfaa.FundID = af.FundID 
				right outer join #dateRange dr on mfaa.MonthEndingDate = dr.MonthEndingDate 
				where mfaa.Amount <> 0
				)

		delete	#dateRange
		where	MonthEndingDate < @firstMonthWithExpenses
		set @expenseDateFrom = @firstMonthWithExpenses
	end

--	create table ##dateRange (MonthEndingDate datetime)
--	insert into ##DateRange
--		select MonthEndingDate from #daterange


	declare @t3 datetime
	set @t3 = current_timestamp
	print 'Step_3: ' + cast(datediff(ss, @t2, @t3) as varchar)

	-- Retrieve direct cost information. This information will be used to generate multiple tables in the resultset and as such
	-- is stored in a table variable.
	create table #directCosts (ExpenseAmount money, ExpenseMonth datetime)

	insert into #directCosts

-- Sixth resultset
		select
			sum(isnull(mfa.Amount, 0)) as ExpenseAmount,
			dr.MonthEndingDate as ExpenseMonth
	   	from 
			MonthlyFundActuals mfa
			inner join #accessibleFunds af on mfa.FundID = af.FundID
			right outer join #dateRange dr on mfa.MonthEndingDate = dr.MonthEndingDate
				and mfa.FinancialTypeID = @directCosts
				--and ((isnull(mfa.FundID, 0) = @fundID) or (@fundID = 0))
				--and mfa.MonthEndingDate between @expenseDateFrom and @expenseDateTo
		group by
			dr.MonthEndingDate with ROLLUP

	select * from #directCosts

	
	-- Retrieve revenue information. This information will be used to generate multiple tables in the resultset and as such
	-- is stored in a table variable. This table is populated here to use for direct cost balances even though its data is
	-- not returned until later - see below, tenth table.
	create table #revenue (ExpenseAmount money, ExpenseMonth datetime)
	create index ExpenseMonth on #revenue(ExpenseMonth)
--select 0 as ExpenseAmount, convert(DateTime, getdate(), 101) as ExpenseMonth
		
	-- The tenth table in the resultset is the revenue for each expense month and the aggregate of such total costs
	-- for all of the expense months.
	insert into #revenue
		select
			sum(isnull(-mfa.Amount, 0)) as ExpenseAmount,
			dr.MonthEndingDate as ExpenseMonth
	   	from 
			MonthlyFundActuals mfa
			inner join #accessibleFunds af on mfa.FundID = af.FundID
			right outer join #dateRange dr on mfa.MonthEndingDate = dr.MonthEndingDate
				and mfa.FinancialTypeID = @Revenue
				--and ((isnull(mfa.FundID, 0) = @fundID) or (@fundID = 0))
				--and mfa.MonthEndingDate between @expenseDateFrom and @expenseDateTo
		group by
			dr.MonthEndingDate with rollup
		
	

	create table #directCostBalance (ExpenseAmount money, ExpenseMonth datetime)
	create index ExpenseMonth on #directCostBalance(ExpenseMonth)

	insert into #directCostBalance
	SELECT 
		-SUM(CASE WHEN financialTypeId=1 THEN Amount ELSE 0 END) - Sum(CASE WHEN financialTypeId=2 THEN Amount ELSE 0 END)  as ExpenseAmount,
		dr.MonthEndingDate as ExpenseMonth
		From MonthlyFundActuals  mfa
		inner join #accessibleFunds af on mfa.FundID = af.FundID
		right outer join #dateRange dr on mfa.MonthEndingDate = dr.MonthEndingDate
		where  FinancialTypeID=1 or FinancialTypeID=2 --   (IsNull(FinancialTypeID,0)=1 or IsNull(FinancialTypeID,0)=2 )  
		Group By 
			  dr.MonthEndingDate with rollup

--		select
--			sum(isnull(mfa.Amount, 0)) as ExpenseAmount,
--			dr.MonthEndingDate as ExpenseMonth
--	   	from 
--			MonthlyFundActuals mfa
--			inner join #accessibleFunds af on mfa.FundID = af.FundID
--			right outer join #dateRange dr on mfa.MonthEndingDate = dr.MonthEndingDate
--				and mfa.FinancialTypeID = 5
--				and ((isnull(mfa.FundID, 0) = @fundID) or (@fundID = 0))
--				and mfa.MonthEndingDate between @expenseDateFrom and @expenseDateTo
--		group by
--			dr.MonthEndingDate with rollup
	select * from #directCostBalance

--		select r.ExpenseAmount - d.ExpenseAmount, r.ExpenseMonth
--		from #revenue r inner join #directCosts d on r.ExpenseMonth = d.ExpenseMonth
--	
--
--	select ExpenseAmount, convert(DateTime, ExpenseMonth, 101) as ExpenseMonth from #directCostBalance
--	union all
--	select isnull(sum(ExpenseAmount), 0) as ExpenseAmount, null as ExpenseMonth from #directCostBalance


	create table #indirectCosts (ExpenseAmount money, ExpenseMonth datetime)

	insert into #indirectCosts

-- Eighth

		select
			sum(isnull(mfa.Amount, 0)) as ExpenseAmount,
			dr.MonthEndingDate as ExpenseMonth
	   	from 
			MonthlyFundActuals mfa
			inner join #accessibleFunds af on mfa.FundID = af.FundID
			right outer join #dateRange dr on mfa.MonthEndingDate = dr.MonthEndingDate
				and mfa.FinancialTypeID = @indirectCosts
				and ((isnull(mfa.FundID, 0) = @fundID) or (@fundID = 0))
				and mfa.MonthEndingDate between @expenseDateFrom and @expenseDateTo
		group by
			dr.MonthEndingDate with rollup

select * from #indirectCosts

	-- Retrieve total cost information. This information will be used to generate multiple tables in the resultset and as such
	-- is stored in a table variable.
	create table #totalCosts (ExpenseAmount money, ExpenseMonth datetime)

	insert into #totalCosts
	SELECT 
		SUM(CASE WHEN financialTypeId=2 THEN Amount ELSE 0 END) + Sum(CASE WHEN financialTypeId=3 THEN Amount ELSE 0 END)  as ExpenseAmount,
		dr.MonthEndingDate as ExpenseMonth
		From MonthlyFundActuals  mfa
		inner join #accessibleFunds af on mfa.FundID = af.FundID
		right outer join #dateRange dr on mfa.MonthEndingDate = dr.MonthEndingDate
		where  FinancialTypeID=2 or FinancialTypeID=3
		Group By 
			  dr.MonthEndingDate with rollup
--		select
--			sum(isnull(mfa.Amount, 0)) as ExpenseAmount,
--			dr.MonthEndingDate as ExpenseMonth
--	   	from 
--			MonthlyFundActuals mfa
--			inner join #accessibleFunds af on mfa.FundID = af.FundID
--			right outer join #dateRange dr on mfa.MonthEndingDate = dr.MonthEndingDate
--				and mfa.FinancialTypeID = @TotalCost
--				and ((isnull(mfa.FundID, 0) = @fundID) or (@fundID = 0))
--				and mfa.MonthEndingDate between @expenseDateFrom and @expenseDateTo
--		group by
--			dr.MonthEndingDate with rollup
	select * from #totalCosts

	select * from #revenue

	-- Retrieve cash balance information. This information will be used to generate multiple tables in the resultset and as such
	-- is stored in a table variable.
	create table #cashBalance (ExpenseAmount money, ExpenseMonth datetime)

	insert into #cashBalance
		select
			-(sum(isnull(revenue.AmountTodate, 0))+sum(isnull(DirectCost.AmountTodate, 0))+sum(isnull(IndirectCost.AmountTodate, 0))) as ExpenseAmount,
			dr.MonthEndingDate as ExpenseMonth
	   	from 
			#accessibleFunds af
			cross join #dateRange dr 
			left outer join MonthlyFundActuals Revenue on Revenue.FundID = af.FundID and Revenue.FinancialTypeID = @revenue 
						 and Revenue.MonthEndingDate = 	(Select max(Revenue1.MonthEndingDate) from MonthlyFundActuals Revenue1 
														 where Revenue1.fundid = Revenue.fundid 
																and Revenue1.FinancialTypeID = Revenue.FinancialTypeID 
																and Revenue1.MonthEndingDate <= dr.MonthEndingDate)

			left outer join MonthlyFundActuals IndirectCost on IndirectCost.FundID = af.FundID and IndirectCost.FinancialTypeID = @indirectCosts 
						and IndirectCost.MonthEndingDate = (Select max(IndirectCost1.MonthEndingDate) from MonthlyFundActuals IndirectCost1 
														 where IndirectCost1.fundid = IndirectCost.fundid 
																and IndirectCost1.FinancialTypeID = IndirectCost.FinancialTypeID 
																and IndirectCost1.MonthEndingDate <= dr.MonthEndingDate)

			left outer join MonthlyFundActuals DirectCost on DirectCost.FundID = af.FundID and DirectCost.FinancialTypeID = @directCosts 
						and DirectCost.MonthEndingDate =(Select max(DirectCost1.MonthEndingDate) from MonthlyFundActuals DirectCost1 
														 where DirectCost1.fundid = DirectCost.fundid 
																and DirectCost1.FinancialTypeID = DirectCost.FinancialTypeID 
																and DirectCost1.MonthEndingDate <= dr.MonthEndingDate)
		group by
			dr.MonthEndingDate
		order by
			dr.MonthEndingDate

	-- The eleventh table in the resultset is the cash balance for each expense month and the aggregate of such total costs
	-- for all of the expense months.
	select ExpenseAmount, convert(DateTime, ExpenseMonth, 101) as ExpenseMonth from #cashBalance
	union all
	select isnull(ExpenseAmount, 0) as ExpenseAmount, null as ExpenseMonth from #cashBalance 
	where expensemonth = (select max(b.expensemonth) from #cashbalance b)
	
	if (@incomingFundNumber <> '')
		exec dbo.GetProjectHeader @incomingFundNumber, null

	-- Retrieve grand total information.
	select
		dc.ExpenseAmount as DirectCostsTotal,
		dcb.ExpenseAmount as DirectCostBalanceTotal,
		ic.ExpenseAmount as IndirectCostsTotal,
		tc.ExpenseAmount as TotalCostsTotal,
		r.ExpenseAmount as RevenueTotal,
		cb.ExpenseAmount as CashBalanceTotal
	from
		(select ExpenseAmount from #directCosts where ExpenseMonth is null) dc,
		(select ExpenseAmount from #directCostBalance where ExpenseMonth is null) dcb,
		(select ExpenseAmount from #indirectCosts where ExpenseMonth is null) ic,
		(select ExpenseAmount from #totalCosts where ExpenseMonth is null) tc,
		(select ExpenseAmount from #revenue where ExpenseMonth is null) r,
		(select isnull(ExpenseAmount, 0) as ExpenseAmount from #cashBalance
		 where expensemonth = (select max(b.expensemonth) from #cashbalance b)) cb

--		(select isnull(sum(ExpenseAmount), 0) as ExpenseAmount from #directCosts) dc,
--		--(select isnull(sum(ExpenseAmount), 0) as ExpenseAmount from #directCostBalance) dcb,
--		(select isnull(sum(ExpenseAmount), 0) as ExpenseAmount from #indirectCosts) ic,
--		(select isnull(sum(ExpenseAmount), 0) as ExpenseAmount from #totalCosts) tc,
--		(select isnull(sum(ExpenseAmount), 0) as ExpenseAmount from #revenue) r,
--		(select isnull(ExpenseAmount, 0) as ExpenseAmount from #cashBalance
--		 where expensemonth = (select max(b.expensemonth) from #cashbalance b)) cb


	drop table #cashBalance
	drop table #indirectCosts
	drop table #directCostBalance
	drop table #revenue
	drop table #directCosts
	drop table #totalCosts
	--drop table #accountCategory
	--drop table #lookUp
	drop table #dateRange
	drop table #accessibleFunds
end











GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Creating [dbo].[GetExpenseInfo_Category_Month]'
GO






CREATE procedure [dbo].[GetExpenseInfo_Category_Month]
(   @SessionID varchar(100),
	@domainUserID int,
	@includeProgramProjects bit = null,
	@fundNumber varchar(8) = null,
	@folderNumber varchar(16) = null,
	@bicsNumber varchar(10) = null,
	@walkerNumber varchar(10) = null,
	@sponsorNumber varchar(32) = null,
	@sponsorName varchar(64) = null,
	@sponsorTypeID int = null,
	@agreementTypeID int = null,
	@activityCode varchar(4)= null,
	@locationID int = null,
	@budgetStartDate datetime = null,
	@budgetEndDate datetime = null,
	@projectStartDate datetime = null,
	@projectEndDate datetime = null,
	@piID int = null,
	@chiefCodeList varchar(1000) = null,
	@sponsorGroupTypeID int = null,
	@budgetEndingDays int = null,
	@projectEndingDays int = null,
	@fundCreatedDays int = null,
	@lowBalance decimal(17,2) = null,
	@highBalance decimal(17,2) = null,
	@agreementStatusTypeList varchar(50)= null,
	@fundStatusTypeID int	= null,
	@categoryID int = null,
	@accountNumber varchar(10) = null,
	@expenseDateFrom datetime = null,
	@expenseDateTo datetime = null,
	@incomingFundNumber varchar(8) = null,
	@monthEndingDate datetime = null
)
as
begin
	set nocount on

	declare @accountID int
	if isnull(@accountNumber,'') = ''
		set @accountID = 0
	else
		set @accountID = (select Id from FinAccount where Number = @accountNumber)

	set @includeProgramProjects = isnull(@includeProgramProjects, 0)
	set @fundNumber = isnull(@fundNumber, '')
	set @folderNumber = isnull(@folderNumber, '')
	set @bicsNumber = isnull(@bicsNumber, '')
	set @walkerNumber = isnull(@walkerNumber, '')
	set @sponsorNumber = isnull(@sponsorNumber, '')
	set @sponsorName = isnull(@sponsorName, '')
	set @sponsorTypeID = isnull(@sponsorTypeID, 0)
	set @agreementTypeID = isnull(@agreementTypeID, 0)
	set @activityCode = isnull(@activityCode, '')
	set @locationID = isnull(@locationID, 0)
	set @budgetStartDate = isnull(@budgetStartDate, '01/01/1900')
	set @budgetEndDate = isnull(@budgetEndDate, '01/01/1900')
	set @projectStartDate = isnull(@projectStartDate, '01/01/1900')
	set @projectEndDate = isnull(@projectEndDate, '01/01/1900')
	set @piID = isnull(@piID, 0)
	set @chiefCodeList = isnull(@chiefCodeList, '')
	set @sponsorGroupTypeID = isnull(@sponsorGroupTypeID, 0)
	set @budgetEndingDays = isnull(@budgetEndingDays, 0)
	set @projectEndingDays = isnull(@projectEndingDays, 0)
	set @fundCreatedDays = isnull(@fundCreatedDays, 0)
	set @lowBalance = isnull(@lowBalance, -922337203685477)
	set @highBalance = isnull(@highBalance, 922337203685477)
	set @agreementStatusTypeList = isnull(@agreementStatusTypeList, '')
	set @fundStatusTypeID = isnull(@fundStatusTypeID, 1)
	set @categoryID = isnull(@categoryID, 0)
	set @accountID = isnull(@accountID, 0)
	set @incomingFundNumber = isnull(@incomingFundNumber, '')
	set @monthEndingDate = isnull(@monthEndingDate, '')

	declare @directCosts int
	set @directCosts = 2

	declare @indirectCosts int
	set @indirectCosts = 3

	declare @revenue int
	set @revenue = 1

	declare @TotalCost int
	set @TotalCost = 4

	declare @CashBalance int
	set @CashBalance = 5

	declare @awardedBudgetTypeId int
	set @awardedBudgetTypeId = 3

	declare @viewFinancialInfoBitValue int
	set @viewFinancialInfoBitValue = 4

	declare @viewPendingAgreementsBitValue int 
	set @viewPendingAgreementsBitValue = 32

	declare @authorizedRightsBitMask int
	set @authorizedRightsBitMask = @viewFinancialInfoBitValue + @viewPendingAgreementsBitValue

	declare @t0 datetime
	set @t0 = current_timestamp

	-- Compute the fund ID based on whether or not the invocation is from an overview or detail context. In the former case,
	-- the @incomingFundNumber is not specified. In the later case, the specified fund number will only be accepted for
	-- further processing only if the specified user has access to that fund.

	declare @fundID int
	if (@incomingFundNumber = '')
		set @fundId = 0
	else
	begin
		select @fundID = [ID] from AgrFund where FundNumber = @incomingFundNumber
		if not exists(select 1 from dbo.CheckFundAccess(@domainUserID, @fundID))
		begin
			declare @message varchar(255)
			set @message = 'User does not have access to fund number ' + @incomingFundNumber
			raiserror(@message, 16, 1)
			return
		end
	end

	-- Generate a list of funds that are accessible to the specified user. When in the detail context, there would only
	-- be one fund to worry about. Since this list of accessible funds is used multiple times, the list is stored in
	-- a table variable.

	create table #accessibleFunds (FundID int primary key, AccessLevel int default 0)

	IF OBJECT_ID('tempdb..#TempFundCollection') is not null drop table #TempFundCollection
	create table #TempFundCollection (FundID int not null, AccessLevel int not null)

	If (@incomingFundNumber = '') begin
		exec GetFundCollection @SessionId, @domainUserID
		Create Unique Index FundId on #TempFundCollection (FundId)
	end
	else
		insert into #TempFundCollection (FundID,AccessLevel) values (@fundID,32767)

	insert into #accessibleFunds
		select * from #TempFundCollection

--	if (@incomingFundNumber = '')
--		insert into #accessibleFunds
--			exec FilterFunds @domainUserID, @authorizedRightsBitMask, @includeProgramProjects,
--				@fundNumber, @folderNumber, @bicsNumber, @walkerNumber, @sponsorNumber, @sponsorName,
--				@sponsorTypeID, @agreementTypeID, @activityCode, @locationID, @budgetStartDate, @budgetEndDate,
--				@projectStartDate, @projectEndDate, @piID, @chiefCodeList, @sponsorGroupTypeID,
--				@budgetEndingDays, @projectEndingDays, @fundCreatedDays, @lowBalance, @highBalance,
--				@agreementStatusTypeList, @fundStatusTypeID
--	else
--		insert into #accessibleFunds (FundID) values (@fundID)

	declare @t1 datetime
	set @t1 = current_timestamp
	print 'Step_1: ' + cast(datediff(ss, @t0, @t1) as varchar)

	-- The expense date range should be from the first day of the 'from' month/year to the last day of the 'to' month/year.
	-- The 'to' date is clamped to the first day of the current month/year.
	-- There are three scenairos to handle:
	-- 1. Both dates are specified
	-- 2. Neither dates are specified
	-- 3. One of the dates is specified
	-- 3a. If the 'from' date is specified, the 'to' date is the mininum of the last gl close date and the 'from' + 12 months
	-- 3b. If the 'to' date is specified, the 'from' date is 'to' - 12 months

	Declare @refreshDatesTable table (glPostAsOfDate datetime,salaryAsOfDate datetime, poapAsOfDate datetime)

	Insert into @refreshDatesTable Exec GetRefreshDates

	Declare @glPostAsOfDate DateTime
	select @glPostAsOfDate = glPostAsOfDate from @refreshDatesTable

	if ((@expenseDateTo is null) or (@expenseDateTo > @glPostAsOfDate))
		set @expenseDateTo = @glPostAsOfDate

	if (@expenseDateFrom is null)
		set @expenseDateFrom = '01/01/1900'		--dateadd(day, 1, dateadd(month, -12, @expenseDateTo))
	else
		set @expenseDateFrom = dateadd(day, -datepart(day, @expenseDateFrom) + 1, @expenseDateFrom)

	-- Retrieve the list of month-end dates between the from and to date range. This is saved in a table variable
	-- for later reuse.
	create table #dateRange ([ID] int primary key identity(1, 1), MonthEndingDate datetime)

	insert into #dateRange
		select Dates from dbo.GetDateRanges(@expenseDateFrom, @expenseDateTo)

	declare @t2 datetime
	set @t2 = current_timestamp
	print 'Step_2: ' + cast(datediff(ss, @t1, @t2) as varchar)

--start
	declare  @FinAccts table (CategoryID int, CategoryName varchar(50), 
		AccountID int, AccountNumber varchar(50), SortOrder int)

	insert into  @FinAccts
	select distinct fc.[ID],
			fc.[Name],
			fa.[ID],
			fa.Number + ' - ' + [Description],
			fc.SortOrder
	from 
		FinAccount fa 
		inner join FinCategory fc on fc.[ID] = fa.FinCategoryID
	join MonthlyFundAccountActuals mfaa on mfaa.AccountID = fa.ID
	join #accessibleFunds af on mfaa.FundID = af.FundID
	join #DateRange dr on mfaa.MonthEndingDate = dr.MonthEndingDate


	where fc.[Name] not in ('INDIRECT COSTS', 'INVESTMENT INCOME', 'OTHER INCOME')
	and (fc.[ID] = @categoryID or @categoryID = 0) 
	and (fa.ID = @accountID or @accountID = 0)


	if @expenseDateFrom = '1900-01-01 00:00:00'
	begin
		declare @firstMonthWithExpenses datetime
		set @firstMonthWithExpenses = (
			select Min( mfaa.MonthEndingDate )
				from MonthlyFundAccountActuals mfaa
				inner join @FinAccts fa on mfaa.AccountID = fa.AccountID
				inner join #accessibleFunds af on mfaa.FundID = af.FundID 
				right outer join #dateRange dr on mfaa.MonthEndingDate = dr.MonthEndingDate 
				where mfaa.Amount <> 0
				)
				

		delete	#dateRange
		where	MonthEndingDate < @firstMonthWithExpenses
		set @expenseDateFrom = @firstMonthWithExpenses
	end

	declare @Category table (CategoryID int, CategoryName varchar(50), SortOrder int)

	insert into @Category
	select distinct fa.CategoryID,  fa.CategoryName, fa.SortOrder 
	from @finaccts fa

	select  ct.CategoryID,  ct.CategoryName, ct.SortOrder, ct.MonthEndingDate  as ExpenseMonth,
		IsNull(Sum(mfaa.Amount),0) as ExpenseAmount, 0 as AccountID
		from 
			MonthlyFundAccountActuals mfaa
			join @FinAccts fa on mfaa.AccountID = fa.AccountID
			join #accessibleFunds af on mfaa.FundID = af.FundID
			right join (	
				select CategoryID,  CategoryName, SortOrder, MonthEndingDate 
				from @Category cross join #DateRange dx
				) ct on  fa.CategoryID = ct.CategoryID and ct.MonthEndingDate = mfaa.MonthEndingDate
		group by ct.CategoryID, ct.CategoryName, ct.SortOrder, ct.MonthEndingDate 
		order by ct.SortOrder, ct.MonthEndingDate 

	drop table #dateRange
	drop table #accessibleFunds
end










GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Altering [dbo].[DeleteHierarchyFromInsight]'
GO
  
/***************************************************************************            
* Name:   MapAgrSubContractorChangesFromInfoEd            
* Purpose:  Updates the Insight data with changes from InfoEd.            
*            
***************************************************************************/            
ALTER PROCEDURE DeleteHierarchyFromInsight           
AS            
BEGIN            
          
SET NOCOUNT ON            
   Begin Try          
  begin transaction DeleteHierarchyFromInsight         
      
 delete from AgrAgreementHierarchy         
            
    Where AgrAgreementHierarchy.FolderNumber  in   
  (select  FolderNumber from Stg_IE_AgrAgreementHierarchy where ParentFolderNumber is null)  
          
           
  commit transaction DeleteHierarchyFromInsight          
 End Try           
    BEGIN CATCH          
  DECLARE           
   @ErrorMessage    NVARCHAR(4000),          
   @ErrorNumber     INT,          
   @ErrorSeverity   INT,          
   @ErrorState      INT,          
   @ErrorLine       INT,          
   @ErrorProcedure  NVARCHAR(200);          
          
  -- Assign variables to error-handling functions that           
  -- capture information for RAISERROR.          
  SELECT           
   @ErrorNumber = ERROR_NUMBER(),          
   @ErrorSeverity = ERROR_SEVERITY(),          
   @ErrorState = ERROR_STATE(),          
   @ErrorLine = ERROR_LINE(),          
   @ErrorProcedure = ISNULL(ERROR_PROCEDURE(), '-');          
          
  -- Building the message string that will contain original          
  -- error information.          
  SELECT @ErrorMessage =           
   N'Error %d, Level %d, State %d, Procedure %s, Line %d, ' +           
    'Message: '+ ERROR_MESSAGE();          
          
  IF XACT_STATE() <> 0 Rollback transaction DeleteHierarchyFromInsight          
          
  -- Raise an error: msg_str parameter of RAISERROR will contain          
  -- the original error information.          
  RAISERROR           
   (          
   @ErrorMessage,           
   @ErrorSeverity,           
   1,                         
   @ErrorNumber,    -- parameter: original error number.          
   @ErrorSeverity,  -- parameter: original error severity.          
   @ErrorState,     -- parameter: original error state.          
   @ErrorProcedure, -- parameter: original error procedure name.          
   @ErrorLine       -- parameter: original error line number.          
   );          
   return 99          
    END CATCH;          
 SET NOCOUNT OFF            
            
END   

GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Altering [dbo].[GetBudgetOverview]'
GO

/************************************************************************************************
* Name:		GetBudgetOverview
* Purpose:	Stored Procedure for displaying the Budget Overview screen.
*
* PARAMETERS
* Name						Description
* -------------------------	-----------------------------
* @domainUserId				Domain User Id
* @fundId					Fund Id
* @employeeJobMapID			Employee Job MapId
* @endDate					the End date of the month.
* @accountID				Account Id.
* @categoryID				Category Id
*
* ERRORS USED
* Number					Description
* -------------------------	-----------------------------
* n/a
*
* Result Set:
*-----------------------------------------------------------------------------------------------
* Name						Description
* -------------------------	-----------------------------
* n/a
*
* RETURN VALUE
* Name						Description
* -------------------------	-----------------------------
************************************************************************************************/
/************************************************************************************************
query for testing stored procedure (e.g. for performance)
------------------
declare
	  @sessionId				varchar(100)
	, @domainUserId				INTEGER	
	, @includeProgramProjects		BIT	
	, @fundNumber				VARCHAR(8)	
	, @folderNumber				VARCHAR(16)	
	, @bicsNumber				VARCHAR(10)	
	, @walkerNumber				VARCHAR(10)	
	, @sponsorNumber			VARCHAR(32)	
	, @sponsorName				VARCHAR(64)	
	, @sponsorTypeId			INTEGER		
	, @agreementTypeId			INTEGER		
	, @activityCode				VARCHAR(4)	
	, @locationId				INTEGER		
	, @budgetStartDate			DATETIME	
	, @budgetEndDate			DATETIME	
	, @projectStartDate			DATETIME	
	, @projectEndDate			DATETIME	
	, @piId					INTEGER		
	, @chiefCodeList			VARCHAR(1000)	
	, @sponsorGroupTypeId			INTEGER			
	, @budgetEndingDays			INTEGER		
	, @projectEndingDays			INTEGER		
	, @fundCreatedDays			INTEGER		
	, @lowBalance				DECIMAL(17,2)	
	, @highBalance				DECIMAL(17,2)	
	, @agreementStatusTypeList		VARCHAR(50)		
	, @fundStatusTypeId			INTEGER		
	, @currentDateTime			DATETIME	
	, @categoryId				INTEGER		
	, @accountId				INTEGER		
	, @glPostAsOfDate			DATETIME	
	, @includeUserOrders			BIT			

select
	  @sessionId				= 'ppdetz55yt4hh0ip1ea0vt45'
	, @domainUserId				= 4025
	, @includeProgramProjects		= null
	, @fundNumber				= null
	, @folderNumber				= null
	, @bicsNumber				= null
	, @walkerNumber				= null
	, @sponsorNumber			= null
	, @sponsorName				= null
	, @sponsorTypeId			= null
	, @agreementTypeId			= null
	, @activityCode				= null
	, @locationId				= null
	, @budgetStartDate			= null
	, @budgetEndDate			= null
	, @projectStartDate			= null
	, @projectEndDate			= null
	, @piId					= 0
	, @chiefCodeList			= ''
	, @sponsorGroupTypeId			= null
	, @budgetEndingDays			= null
	, @projectEndingDays			= null
	, @fundCreatedDays			= null
	, @lowBalance				= null
	, @highBalance				= null
	, @agreementStatusTypeList		= ''
	, @fundStatusTypeId			= null
	, @currentDateTime			= null
	, @categoryId				= null
	, @accountId				= null
	, @glPostAsOfDate			= '6/30/2007'
	, @includeUserOrders			= null

exec GetBudgetOverview
	  @sessionId		
	, @domainUserId		
	, @includeProgramProjects
	, @fundNumber		
	, @folderNumber		
	, @bicsNumber		
	, @walkerNumber		
	, @sponsorNumber	
	, @sponsorName		
	, @sponsorTypeId	
	, @agreementTypeId	
	, @activityCode		
	, @locationId		
	, @budgetStartDate	
	, @budgetEndDate	
	, @projectStartDate	
	, @projectEndDate	
	, @piId			
	, @chiefCodeList	
	, @sponsorGroupTypeId	
	, @budgetEndingDays	
	, @projectEndingDays	
	, @fundCreatedDays	
	, @lowBalance		
	, @highBalance		
	, @agreementStatusTypeList
	, @fundStatusTypeId	
	, @currentDateTime	
	, @categoryId		
	, @accountId		
	, @glPostAsOfDate	
	, @includeUserOrders	

*************************************************************************************************/
--Modifications:
--08/116/2007	JML Performance improvements
--------------------------------------------
ALTER PROCEDURE [dbo].[GetBudgetOverview]
(
	  @sessionId				varchar(100)
	, @domainUserId				INTEGER					--1)
	, @includeProgramProjects	BIT				= null	--2)
	, @fundNumber				VARCHAR(8)		= null	--3)
	, @folderNumber				VARCHAR(16)		= null	--4)
	, @bicsNumber				VARCHAR(10)		= null	--5)
	, @walkerNumber				VARCHAR(10)		= null	--6)
	, @sponsorNumber			VARCHAR(32)		= null	--7)
	, @sponsorName				VARCHAR(64)		= null	--8)
	, @sponsorTypeId			INTEGER			= null	--9)
	, @agreementTypeId			INTEGER			= null	--10)
	, @activityCode				VARCHAR(4)		= null	--11)
	, @locationId				INTEGER			= null	--12)
	, @budgetStartDate			DATETIME		= null	--13)
	, @budgetEndDate			DATETIME		= null	--14)
	, @projectStartDate			DATETIME		= null	--15)
	, @projectEndDate			DATETIME		= null	--16)
	, @piId						INTEGER			= null	--17)
	, @chiefCodeList			VARCHAR(1000)	= null	--18)
	, @sponsorGroupTypeId		INTEGER			= null	--19)
	, @budgetEndingDays			INTEGER			= null	--20)
	, @projectEndingDays		INTEGER			= null	--21)
	, @fundCreatedDays			INTEGER			= null	--22)
	, @lowBalance				DECIMAL(17,2)	= null	--23)
	, @highBalance				DECIMAL(17,2)	= null	--24)
	, @agreementStatusTypeList	VARCHAR(50)		= null	--25)
	, @fundStatusTypeId			INTEGER			= null	--26)
	, @currentDateTime			DATETIME		= null	--27)
	, @categoryId				INTEGER			= null	--28)
	, @accountId				INTEGER			= null	--29)
	, @glPostAsOfDate			DATETIME		= null	--30)
	, @includeUserOrders		BIT				= null	--31)
)
AS
BEGIN
	SET NOCOUNT ON

	-- set defaults correctly for all optional parameters
	SET	@includeProgramProjects		= ISNULL(@includeProgramProjects, 0)
	SET	@sponsorTypeId				= ISNULL(@sponsorTypeId, 0)
	SET	@agreementTypeId			= ISNULL(@agreementTypeId, 0)
	SET	@locationId					= ISNULL(@locationId, 0)
	SET	@budgetStartDate			= ISNULL(@budgetStartDate, '')
	SET	@budgetEndDate				= ISNULL(@budgetEndDate, '')
	SET	@projectStartDate			= ISNULL(@projectStartDate, '')
	SET	@projectEndDate				= ISNULL(@projectEndDate, '')
	SET	@piId						= ISNULL(@piId, 0)
	SET	@chiefCodeList				= ISNULL(@chiefCodeList, '')
	SET	@sponsorGroupTypeId			= ISNULL(@sponsorGroupTypeId, 0)
	SET	@budgetEndingDays			= ISNULL(@budgetEndingDays, 0)
	SET	@projectEndingDays			= ISNULL(@projectEndingDays, 0)
	SET	@fundCreatedDays			= ISNULL(@fundCreatedDays, 0)
	SET	@lowBalance					= ISNULL(@lowBalance, -922337203685477)
	SET	@highBalance				= ISNULL(@highBalance, 922337203685477)
	SET	@agreementStatusTypeList	= ISNULL(@agreementStatusTypeList, '')
	SET	@fundStatusTypeId			= ISNULL(@fundStatusTypeId, 1)
	SET	@currentDateTime			= ISNULL(@currentDateTime, 0)
	SET	@glPostAsOfDate				= ISNULL(@glPostAsOfDate, '')
	SET	@includeUserOrders			= ISNULL(@includeUserOrders, 0)

	/******************************************************************************
		Constant Declarations and Assigning values to the constants.
	******************************************************************************/
	DECLARE @viewFinancialInfoBitValue		int
	DECLARE @viewPendingAgreementsBitValue	int
	DECLARE @authorizedRightsBitMask		int

	SET @viewFinancialInfoBitValue		= 4
	SET @viewPendingAgreementsBitValue	= 32
	SET	@authorizedRightsBitMask		= @viewFinancialInfoBitValue + @viewPendingAgreementsBitValue

	DECLARE @categoryIndirectCosts		INTEGER
	DECLARE @categoryInvestmentIncome	INTEGER
	DECLARE @categoryOtherIncome		INTEGER
	DECLARE @directCosts				INTEGER
	DECLARE @indirectCosts				INTEGER
	DECLARE @revenue					INTEGER
	DECLARE @ProjectAccountingCycle		INTEGER
	DECLARE @FiscalAccountingCycle		INTEGER
	DECLARE @budgetEndingDate			DATETIME
	DECLARE @monthEndingDate			DATETIME
	DECLARE @budgetViewTypeId			INTEGER
	DECLARE @yearEndDate				VARCHAR(6)
	DECLARE @userOrderTypePO			INTEGER
	DECLARE @userOrderTypeTravelVoucher	INTEGER
	DECLARE @userOrderTypeCheckRequest	INTEGER
	DECLARE @userOrderTypePettyCash	INTEGER

	SET @yearEndDate				=  '09/30/'
	SET @categoryIndirectCosts		= 9
	SET @categoryInvestmentIncome	= 10
	SET @categoryOtherIncome		= 14
	SET @directCosts				= 2
	SET @indirectCosts				= 3
	SET @revenue					= 1
	SET @ProjectAccountingCycle		= 3
	SET @FiscalAccountingCycle		= 2
	SET @budgetEndingDate			= ''
	SET @budgetViewTypeId			= 3 --Awarded
	SELECT @currentDateTime			= getdate()
	SET @userOrderTypePO			= 1
	SET @userOrderTypeTravelVoucher	= 2
	SET @userOrderTypeCheckRequest	= 3
	SET @userOrderTypePettyCash		= 5

	/*
	Save the last GL post date as the month ending date used to SELECT budgets,
	expenses, and revenue
	*/
	SET @monthEndingDate = @glPostAsOfDate

	DECLARE @today DATETIME
	DECLARE @currentYear INTEGER
	SET @today = GETDATE()
	IF MONTH(@glPostAsOfDate) > 9
		SET @currentYear = YEAR(@glPostAsOfDate) + 1
	ELSE
		SET @currentYear = YEAR(@glPostAsOfDate)

	-- Temp table to hold the Category data.
	DECLARE @Category TABLE
	(
		CategoryId			INTEGER,
		SortOrder			INTEGER,
		Category			VARCHAR(256),
		Budget				MONEY,
		Expense				MONEY,
		Encumbrance			MONEY,
		AccountNumber		varchar(10),
		BalanceAvailable	AS (ISNULL(Budget,0) - ISNULL(Expense,0) - ISNULL(Encumbrance,0)),
		AccountId			AS 0
	)

	-- Table variable to hold the UserOrder Account data.
	DECLARE @UserOrderAccount TABLE
	(
		CategoryId			INTEGER,
		SortOrder			INTEGER,
		AccountId			INTEGER,
		AccountNumber		VARCHAR(10),
		AccountDescription	VARCHAR(255),
		Budget				MONEY,
		Expense				MONEY,
		Encumbrance			MONEY,
		BalanceAvailable	AS (-ISNULL(Encumbrance,0))
	)

	-- Temp table to hold the Account Data.
	CREATE TABLE #Account
	(
		CategoryId			INTEGER,
		SortOrder			INTEGER,
		AccountId			INTEGER,
		AccountNumber		VARCHAR(10),
		AccountDescription	VARCHAR(255),
		Budget				MONEY,
		Expense				MONEY
	)

	CREATE TABLE  #AccountEnc
	(
		CategoryId			INTEGER,
		SortOrder			INTEGER,
		AccountId			INTEGER,
		Encumbrance			MONEY
	)

	-- Temp table to hold the Indirect Costs Data.
	DECLARE @IndirectCostsTable TABLE
	(
		Budget				MONEY,
		Expense				MONEY,
		Encumbrance			MONEY,
		BalanceAvailable	AS (ISNULL(Budget,0) - ISNULL(Expense,0) - ISNULL(Encumbrance,0))
	)

	-- Temp table to hold the Revenue amount.
	DECLARE @RevenueTable TABLE
	(
		Revenue				MONEY
	)

	-- Temp table to hold the Prior Year Balance
	DECLARE @PriorYearBalance TABLE
	(
		PriorYearBalance	MONEY
	)

	/*create table #filteredFunds (FundID int primary key, AccessLevel int default 0)
	insert into #filteredFunds
		exec FilterFunds
			 @domainUserId				--1)
			,@authorizedRightsBitMask	--2)
			,@includeProgramProjects	--3)
			,@fundNumber				--4)
			,@folderNumber				--5)
			,@bicsNumber				--6)
			,@walkerNumber				--7)
			,@sponsorNumber				--8)
			,@sponsorName				--9)
			,@sponsorTypeId				--10)
			,@agreementTypeId			--11)
			,@activityCode				--12)
			,@locationId				--13)
			,@budgetStartDate			--14)
			,@budgetEndDate				--15)
			,@projectStartDate			--16)
			,@projectEndDate			--17)
			,@piId						--18)
			,@chiefCodeList				--19)
			,@sponsorGroupTypeId		--20)
			,@budgetEndingDays			--21)
			,@projectEndingDays			--22)
			,@fundCreatedDays			--23)
			,@lowBalance				--24)
			,@highBalance				--25)
			,@agreementStatusTypeList	--26)
			,@fundStatusTypeId			--27)
*/
	-- declare and populate a table variable with all the fund Ids the domain user has access to
	CREATE TABLE #AccessibleFunds (FundId INTEGER, AccountingCycleTypeId INTEGER)

	declare @fundCollectionTable varchar(100)
	set @fundCollectionTable = '_FundCollection_' + convert(varchar(20), @domainUserID)

	Exec('INSERT INTO #AccessibleFunds select ff.fundid,af.AccountingCycleTypeId from ' + @fundCollectionTable 
			+ ' ff INNER JOIN AgrAgreement_Fct af (nolock) ON af.FundId = ff.FundId Where ff.SessionID = '''
			+ @SessionID + '''')

	CREATE INDEX FundId on #AccessibleFunds(FundId)


	/******************************************************************************
	 Get the User Order Balance amounts from PurUserOrderDistribution.
	 This amount will be displayed only in Encumbrance column and hence
	 other columns i.e. Budget and Expense are zero.
	******************************************************************************/
	IF @includeUserOrders = 1 Begin

		-- insert category total for user orders
		INSERT	INTO	@Category
		SELECT			  99 AS 'CategoryId'
						, 99 AS 'SortOrder'
						, 'USER ORDERS' AS 'Category'
						, 0 AS 'Budget'
						, 0 AS 'Expense'
						, SUM(ISNULL(uod.Amount,0)) AS 'Encumbrance'
						,null
		FROM			#AccessibleFunds a
		INNER JOIN		PurUserOrderDistribution uod (nolock) ON a.FundId = uod.AgrFundId
		INNER JOIN		PurUserOrderHeader uoh (nolock) ON uod.PurUserOrderHeaderId = uoh.Id
		WHERE uoh.PurUserOrderTypeId IN (@userOrderTypePO,@userOrderTypeTravelVoucher,@userOrderTypeCheckRequest, @userOrderTypePettyCash)
			  AND uoh.Id NOT IN (SELECT	ros.InsightId FROM PurReconciledOrder_Src ros
								 WHERE	ros.OrderTypeId = uoh.PurUserOrderTypeId)

		-- insert accounts totals for user orders
		INSERT	INTO @UserOrderAccount
		SELECT		  99 AS 'CategoryId'
					, 99 AS 'SortOrder'
					, fa.[Id] AS 'AccountId'
					, fa.Number AS 'AccountNumber'
					, fa.[Description] AS 'AccountDescription'
					, 0 AS 'Budget'
					, 0 AS 'Expense'
					, SUM(ISNULL(uod.Amount,0)) AS 'Encumbrance'
		FROM #AccessibleFunds a
		INNER JOIN	PurUserOrderDistribution uod (nolock) ON a.FundId = uod.AgrFundId
		INNER JOIN	PurUserOrderHeader uoh (nolock) ON uod.PurUserOrderHeaderId = uoh.Id
		INNER JOIN	FinAccount fa (nolock) ON uod.AccountId = fa.[Id]
		WHERE uoh.PurUserOrderTypeId IN (@userOrderTypePO,@userOrderTypeTravelVoucher,@userOrderTypeCheckRequest, @userOrderTypePettyCash)
			  AND uoh.Id NOT IN (SELECT ros.InsightId FROM PurReconciledOrder_Src ros
								 WHERE ros.OrderTypeId = uoh.PurUserOrderTypeId)
		GROUP BY	fa.[Id], fa.Number, fa.[Description]
		ORDER BY	fa.Number , fa.[Description]

	End

	/*
	*****************************************************************************
	 Account Encumbrances
	*****************************************************************************
	*/
	INSERT INTO #AccountEnc
	SELECT
		 fc.[Id] AS 'CategoryId'
		,fc.SortOrder
		,ff.[Id] AS 'AccountId'
		,Encumbrance.EncumbranceAmounts
	FROM FinCategory fc  (nolock)
	INNER JOIN	FinAccount ff (nolock) ON fc.[Id] = ff.FinCategoryId
	LEFT OUTER JOIN
		(SELECT enc.AccountId,
				SUM(ISNULL(enc.Amount,0)) AS 'EncumbranceAmounts'
		 FROM #AccessibleFunds af
		 INNER JOIN	dbo.PurEncumbrance_Fct enc ON enc.FundId = af.FundId
		 GROUP BY	enc.AccountId) Encumbrance 
	ON ff.[Id] = Encumbrance.AccountId
	WHERE fc.[Id] NOT IN (@categoryIndirectCosts,@categoryInvestmentIncome,@categoryOtherIncome)

	/*
	*****************************************************************************
	If the month ending date is the same as the last gl post date then we can 
	eliminate some sub selects and speed up the retrieval.
	*****************************************************************************
	*/
	If @monthEndingDate = @glPostAsOfDate Begin

		/******************************************************************************
		 Account Details
		******************************************************************************/
		INSERT INTO #Account
		SELECT fc.[Id] AS 'CategoryId', fc.SortOrder ,ff.[Id] AS 'AccountId', ff.Number AS 'AccountNumber' 
				,ff.[Description] AS 'AccountDescription', Budgets.BudgetAmounts, Actuals.ActualExpenses
		FROM FinCategory fc  (nolock)
		INNER JOIN	FinAccount ff (nolock) ON fc.[Id] = ff.FinCategoryId
		-- Budgets
		LEFT OUTER JOIN
			(SELECT  cyc.AccountId,sum(ISNULL(cyc.BudgetAmounts,0)) as BudgetAmounts From 
			(SELECT		fab.AccountId,
						CASE WHEN af.AccountingCycleTypeId = @FiscalAccountingCycle THEN 
								SUM(ISNULL(fab.Amount,0)) ELSE SUM(ISNULL(fab.AmountToDate,0))
		  				END  AS 'BudgetAmounts'
			 FROM		#AccessibleFunds af
			 INNER JOIN	MonthlyFundAccountBudget fab (nolock) ON	fab.FundId = af.FundId
			 WHERE		fab.MonthEndingDate = @monthEndingDate 
					AND	fab.BudgetViewTypeId = @budgetViewTypeId
			 GROUP BY af.AccountingCycleTypeId,fab.AccountId) cyc 
			 GROUP BY cyc.AccountId) budgets
		ON ff.[Id] = Budgets.AccountId
		-- Expenses
		LEFT OUTER JOIN
			(SELECT  cyc.AccountId,sum(ISNULL(cyc.ActualExpenses,0)) as ActualExpenses From 
			(SELECT faa.AccountId,
					CASE WHEN af.AccountingCycleTypeId = @FiscalAccountingCycle THEN 
							SUM(ISNULL(faa.Amount,0)) ELSE SUM(ISNULL(faa.AmountToDate,0))
		  				END AS 'ActualExpenses'
			 FROM	#AccessibleFunds af
			 INNER JOIN	MonthlyFundAccountActuals faa (nolock) ON faa.FundId = af.FundId
			 WHERE ((af.AccountingCycleTypeId = @FiscalAccountingCycle AND faa.FiscalYear = @currentYear) OR
						(faa.MonthEndingDate = @monthEndingDate AND af.AccountingCycleTypeId = @ProjectAccountingCycle))
			 GROUP BY af.AccountingCycleTypeId,faa.AccountId) cyc 
			 GROUP BY cyc.AccountId) Actuals
		ON ff.[Id] = Actuals.AccountId
		WHERE fc.[Id] NOT IN (@categoryIndirectCosts,@categoryInvestmentIncome,@categoryOtherIncome)

		/******************************************************************************
			Get Indirect Costs Balances.
		******************************************************************************/
		INSERT INTO @IndirectCostsTable
		SELECT
			(SELECT SUM(FinalTotal.AmountToDate) AS AmountToDate 
			 FROM (SELECT CASE WHEN af.AccountingCycleTypeId = @ProjectAccountingCycle THEN SUM(ISNULL(fb.AmountToDate,0))
								ELSE SUM(ISNULL(fb.Amount,0)) END AS 'AmountToDate'
					FROM #AccessibleFunds af
					INNER JOIN MonthlyFundBudget fb (nolock) ON fb.FundId = af.FundId
					WHERE fb.MonthEndingDate = @monthEndingDate 
					 AND fb.FinancialTypeId = @indirectCosts
					 AND fb.BudgetViewTypeId = @budgetViewTypeId
					GROUP BY af.AccountingCycleTypeId) FinalTotal) AS 'Budgets'
		,	(SELECT	SUM(FinalTotal.AmountToDate) AS AmountToDate
			 FROM (SELECT CASE WHEN af.AccountingCycleTypeId = @ProjectAccountingCycle THEN SUM(ISNULL(fa.AmountToDate,0))
								ELSE SUM(ISNULL(fa.Amount,0)) END AS 'AmountToDate'
					FROM #AccessibleFunds af
					INNER JOIN MonthlyFundactuals fa (nolock) ON fa.FundId = af.FundId
					WHERE ((af.AccountingCycleTypeId = @FiscalAccountingCycle AND fa.FiscalYear = @currentYear)
							OR (af.AccountingCycleTypeId = @ProjectAccountingCycle AND fa.MonthEndingDate = @monthEndingDate))
							AND fa.FinancialTypeId = @indirectCosts
					GROUP BY af.AccountingCycleTypeId) FinalTotal) AS 'Actuals'
		,	(SELECT SUM(ISNULL(enc.IndirectCost,0)) AS 'EncumbranceAmounts'
			 FROM dbo.PurEncumbrance_Fct enc (nolock)
			 INNER JOIN	FinAccount fa (nolock) ON fa.[Id] = enc.[AccountId]
			 INNER JOIN	#AccessibleFunds af ON enc.FundId = af.FundId
			 WHERE fa.FinCategoryId NOT IN (@categoryIndirectCosts,@categoryInvestmentIncome,@categoryOtherIncome)
			) Encumbrance

		/******************************************************************************
			Revenue
		******************************************************************************/
		INSERT INTO @RevenueTable
		SELECT -SUM(FinalTotal.AmountToDate) AS AmountToDate
		FROM
			(SELECT CASE WHEN af.AccountingCycleTypeId = @ProjectAccountingCycle THEN SUM(ISNULL(a.AmountToDate,0))
					ELSE SUM(ISNULL(a.Amount,0)) END AS 'AmountToDate'
			 FROM #AccessibleFunds af
			 INNER JOIN	MonthlyFundActuals a (nolock) ON a.FundId = af.FundId
			 WHERE ((af.AccountingCycleTypeId = @FiscalAccountingCycle AND a.FiscalYear = @currentYear) OR 
					(af.AccountingCycleTypeId = @ProjectAccountingCycle AND A.MonthEndingDate = @monthEndingDate))
					AND a.FinancialTypeId = @revenue
			GROUP BY af.AccountingCycleTypeId) FinalTotal
	End

	Else Begin

		/******************************************************************************
		 Account Details
		******************************************************************************/
		INSERT INTO #Account
		SELECT fc.[Id] AS 'CategoryId', fc.SortOrder, ff.[Id] AS 'AccountId', ff.Number AS 'AccountNumber' 
			,ff.[Description] AS 'AccountDescription', Budgets.BudgetAmounts, Actuals.ActualExpenses
		FROM FinCategory fc (nolock)
		INNER JOIN	FinAccount ff (nolock) ON fc.[Id] = ff.FinCategoryId
		-- Budgets
		LEFT OUTER JOIN
			(SELECT	FinalTotal.AccountId, SUM(FinalTotal.BudgetAmounts) AS BudgetAmounts
			 FROM
				(SELECT	fab.AccountId, CASE WHEN af.AccountingCycleTypeId = @ProjectAccountingCycle THEN SUM(ISNULL(fab.AmountToDate,0))
											ELSE SUM(ISNULL(fab.Amount,0)) END AS 'BudgetAmounts'
				FROM #AccessibleFunds af
				INNER JOIN MonthlyFundAccountBudget fab (nolock) ON fab.FundId = af.FundId
				WHERE fab.MonthEndingDate = (SELECT	MAX(fab1.MonthEndingDate) FROM MonthlyFundAccountBudget fab1
											 WHERE fab1.FundId = fab.FundId AND fab1.AccountId = fab.AccountId 
												--	AND fab1.MonthEndingDate <= @monthEndingDate 
													AND fab1.BudgetViewTypeId = fab.BudgetViewTypeId)
						AND fab.BudgetViewTypeId = @budgetViewTypeId
				GROUP BY fab.AccountId, af.AccountingCycleTypeId) FinalTotal
			GROUP BY FinalTotal.AccountId) Budgets
		ON ff.[Id] = Budgets.AccountId
		-- Expenses
		LEFT OUTER JOIN
			(SELECT FinalTotal.AccountId, SUM(FinalTotal.ActualExpenses) AS ActualExpenses
			 FROM
				(SELECT	faa.AccountId,	CASE WHEN af.AccountingCycleTypeId = @ProjectAccountingCycle THEN SUM(ISNULL(faa.AmountToDate,0))
										ELSE SUM(ISNULL(faa.Amount,0)) END AS 'ActualExpenses'
				FROM #AccessibleFunds af
				INNER JOIN	MonthlyFundAccountActuals faa (nolock) ON faa.FundId = af.FundId
				WHERE	((af.AccountingCycleTypeId = @FiscalAccountingCycle AND faa.FiscalYear = @currentYear)
						 OR (af.AccountingCycleTypeId = @ProjectAccountingCycle 
							AND faa.MonthEndingDate = (SELECT MAX(faa1.MonthEndingDate) FROM MonthlyFundAccountActuals faa1
														WHERE	faa.FundId = faa1.FundId AND faa.AccountId = faa1.AccountId)))
				GROUP BY faa.AccountId,af.AccountingCycleTypeId) FinalTotal
			GROUP BY FinalTotal.AccountId) Actuals
		ON ff.[Id] = Actuals.AccountId
		WHERE fc.[Id] NOT IN (@categoryIndirectCosts,@categoryInvestmentIncome,@categoryOtherIncome)

		/******************************************************************************
			Get Indirect Costs Balances.
		******************************************************************************/
		INSERT INTO @IndirectCostsTable
		SELECT
			(SELECT SUM(FinalTotal.AmountToDate) AS AmountToDate 
			 FROM (SELECT CASE WHEN af.AccountingCycleTypeId = @ProjectAccountingCycle THEN SUM(ISNULL(fb.AmountToDate,0))
								ELSE SUM(ISNULL(fb.Amount,0)) END AS 'AmountToDate'
					FROM #AccessibleFunds af
					INNER JOIN MonthlyFundBudget fb (nolock) ON fb.FundId = af.FundId
					WHERE fb.MonthEndingDate = 
						(SELECT	MAX(fb1.MonthEndingDate)
						 FROM	MonthlyFundBudget fb1 (nolock)
						 WHERE	fb1.fundId = fb.fundId  AND fb1.FinancialTypeId = fb.FinancialTypeId
								AND fb1.BudgetViewTypeId = fb.BudgetViewTypeId)
					 AND fb.FinancialTypeId = @indirectCosts
					 AND fb.BudgetViewTypeId = @budgetViewTypeId
					GROUP BY af.AccountingCycleTypeId) FinalTotal) AS 'Budgets'
		,	(SELECT	SUM(FinalTotal.AmountToDate) AS AmountToDate
			 FROM (SELECT CASE WHEN af.AccountingCycleTypeId = @ProjectAccountingCycle THEN SUM(ISNULL(fa.AmountToDate,0))
								ELSE SUM(ISNULL(fa.Amount,0)) END AS 'AmountToDate'
					FROM #AccessibleFunds af
					INNER JOIN MonthlyFundactuals fa (nolock) ON fa.FundId = af.FundId
					WHERE ((af.AccountingCycleTypeId = @FiscalAccountingCycle AND fa.FiscalYear = @currentYear)
							OR (af.AccountingCycleTypeId = @ProjectAccountingCycle AND fa.MonthEndingDate = 
									(SELECT	MAX(fa1.MonthEndingDate)
									 FROM	MonthlyFundactuals fa1 (nolock)
									 WHERE	fa1.fundId = fa.fundId 
											AND fa1.FinancialTypeId = fa.FinancialTypeId)))
							AND fa.FinancialTypeId = @indirectCosts
					GROUP BY af.AccountingCycleTypeId) FinalTotal) AS 'Actuals'
		,	(SELECT SUM(ISNULL(enc.IndirectCost,0)) AS 'EncumbranceAmounts'
			 FROM dbo.PurEncumbrance_Fct enc (nolock)
			 INNER JOIN	FinAccount fa (nolock) ON fa.[Id] = enc.[AccountId]
			 INNER JOIN	#AccessibleFunds af ON enc.FundId = af.FundId
			 WHERE fa.FinCategoryId NOT IN (@categoryIndirectCosts,@categoryInvestmentIncome,@categoryOtherIncome)
			) Encumbrance

		/******************************************************************************
			Revenue
		******************************************************************************/
		INSERT INTO @RevenueTable
		SELECT -SUM(FinalTotal.AmountToDate) AS AmountToDate
		FROM
			(SELECT CASE WHEN af.AccountingCycleTypeId = @ProjectAccountingCycle THEN SUM(ISNULL(a.AmountToDate,0))
					ELSE SUM(ISNULL(a.Amount,0)) END AS 'AmountToDate'
			 FROM #AccessibleFunds af
			 INNER JOIN	MonthlyFundActuals a (nolock) ON a.FundId = af.FundId
			 WHERE ((af.AccountingCycleTypeId = @FiscalAccountingCycle AND a.FiscalYear = @currentYear) OR 
					(af.AccountingCycleTypeId = @ProjectAccountingCycle AND A.MonthEndingDate = 
							(SELECT	MAX(b.MonthEndingDate) FROM	MonthlyFundActuals b 
							 WHERE a.FundId = b.FundId AND a.FinancialTypeId = b.FinancialTypeId)))
					AND a.FinancialTypeId = @revenue
			GROUP BY af.AccountingCycleTypeId) FinalTotal
	End

	/******************************************************************************
		Prior Year Balance
	******************************************************************************/
	-- Retrieve the Previous Fiscal Year.
	DECLARE @previousYear VARCHAR(10)

	Set @previousYear = @currentYear - 1
	Set @previousYear = @yearEndDate + CAST(@previousYear AS VARCHAR(4))

	-- Get the previous year revenue.
	/*
		The prior year revenue is the amount to date revenue from the
		maximum month ending date less than or equal to the prior year
		end date.
	*/
	DECLARE @previousYearRevenue MONEY
	SELECT	@previousYearRevenue = 
			-(SELECT SUM(FinalTotal.AmountToDate) FROM
				( SELECT CASE WHEN af.AccountingCycleTypeId = @ProjectAccountingCycle THEN 0 ELSE SUM(ISNULL(a.AmountToDate,0))
		  				END AS AmountToDate
					FROM #AccessibleFunds af INNER JOIN	MonthlyFundActuals a (nolock) ON a.FundId = af.FundId
					WHERE a.MonthEndingDate = ( SELECT	MAX(b.MonthEndingDate) FROM	MonthlyFundActuals b (nolock) WHERE	b.FundId = a.FundId
												AND	b.FinancialTypeId = a.FinancialTypeId AND b.MonthEndingDate <= @previousYear )
					AND			a.FinancialTypeId = @revenue
					GROUP BY	af.AccountingCycleTypeId
				) FinalTotal )

	-- Get the Previous year Direct Costs and Indirect Costs
	/*
		The prior year expenses is the amount-to-date expenses
		from the maximum month ending date less than or equal 
		to the prior year end date.
	*/
	DECLARE @previousYearDirectCosts MONEY
	DECLARE @previousYearIndirectCosts MONEY

	SELECT	@previousYearDirectCosts = 
			(SELECT	SUM(FinalTotal.AmountToDate) FROM
				(SELECT CASE WHEN af.AccountingCycleTypeId = @ProjectAccountingCycle THEN 0 ELSE SUM(ISNULL(a.AmountToDate,0))
						END AS AmountToDate
				 FROM #AccessibleFunds af INNER JOIN MonthlyFundActuals a (nolock) ON a.FundId = af.FundId
				 WHERE a.MonthEndingDate = (SELECT MAX(b.MonthEndingDate) FROM MonthlyFundActuals b (nolock)
											WHERE b.FundId = a.FundId AND b.FinancialTypeId = a.FinancialTypeId
													AND b.MonthEndingDate <= @previousYear)
						AND	a.FinancialTypeId = @directCosts
				 GROUP BY af.AccountingCycleTypeId) FinalTotal)

	SELECT @previousYearIndirectCosts = 
			(SELECT	SUM(FinalTotal.AmountToDate) FROM
				(SELECT CASE WHEN af.AccountingCycleTypeId = @ProjectAccountingCycle THEN 0 ELSE SUM(ISNULL(a.AmountToDate,0)) 
						END AS AmountToDate
				 FROM #AccessibleFunds af INNER JOIN MonthlyFundActuals a (nolock) ON a.FundId = af.FundId
				 WHERE a.MonthEndingDate = (SELECT	MAX(b.MonthEndingDate) FROM	MonthlyFundActuals b (nolock)
											WHERE	b.FundId = a.FundId AND b.FinancialTypeId = a.FinancialTypeId 
													AND b.MonthEndingDate <= @previousYear)
						AND a.FinancialTypeId = @indirectCosts
				 GROUP BY af.AccountingCycleTypeId) FinalTotal)

	-- Revenue will have negative amount and hence WHEN added up with Total Costs returns the PriorYearBalance'
	INSERT INTO @PriorYearBalance
	SELECT ISNULL(@previousYearRevenue,0) - (ISNULL(@previousYearDirectCosts,0) + ISNULL(@previousYearIndirectCosts,0))

	/******************************************************************************
		Output: Resultset
	******************************************************************************/
	-- a) Category
	INSERT INTO @Category
	SELECT a.CategoryId, a.SortOrder, fc.[Name], SUM(ISNULL(a.Budget,0)), SUM(ISNULL(a.Expense,0)), SUM(ISNULL(b.Encumbrance,0)), null
	FROM #Account a LEFT OUTER JOIN #AccountEnc b ON a.AccountId = b.AccountId INNER JOIN FinCategory fc (nolock) ON a.CategoryId = fc.[Id]
	WHERE (@categoryId IS NULL OR b.CategoryId = @categoryId) AND (@AccountId IS NULL OR a.AccountId = @AccountId)
			AND (ISNULL(a.Budget,0) <> 0 OR ISNULL(a.Expense,0) <> 0 OR ISNULL(b.Encumbrance,0) <> 0 )
	GROUP BY  a.SortOrder, a.CategoryId, fc.[Name]

	SELECT CategoryId, SortOrder, AccountId, AccountNumber, Category, Budget, Expense, Encumbrance, BalanceAvailable
	FROM @Category ORDER BY SortOrder

	-- b) Accounts
	Select a.CategoryId, a.SortOrder, a.AccountId , a.AccountNumber , a.AccountNumber + ' - ' + a.AccountDescription AS 'Category',
			ISNULL(a.Budget,0) AS 'Budget',ISNULL(a.Expense,0) AS 'Expense',ISNULL(b.Encumbrance,0) AS 'Encumbrance',
			(ISNULL(a.Budget,0) - ISNULL(a.Expense,0) - ISNULL(b.Encumbrance,0)) AS 'BalanceAvailable'
	From #Account a INNER JOIN #AccountEnc b ON a.AccountId = b.AccountId
	Where (@categoryId IS NULL OR a.CategoryId = @categoryId) AND (@AccountId IS NULL OR a.AccountId = @AccountId)
			AND (ISNULL(a.Budget,0) <> 0 OR ISNULL(a.Expense,0) <> 0 OR ISNULL(b.Encumbrance,0) <> 0 )
	Union
	Select CategoryId, SortOrder, AccountId, AccountNumber, AccountNumber + ' - ' + AccountDescription as 'Category',
			Budget, Expense, Encumbrance, BalanceAvailable From @UserOrderAccount ORDER BY a.SortOrder, AccountNumber

	-- c) Direct Costs Total
	IF (SELECT COUNT(*) FROM @Category) > 0
		SELECT
			SUM(ISNULL(Budget,0)) AS 'Budget',
			SUM(ISNULL(Expense,0)) AS 'Expense',
			SUM(ISNULL(Encumbrance,0)) AS 'Encumbrance' ,
			SUM(ISNULL(BalanceAvailable,0)) AS 'BalanceAvailable'
		FROM
			@Category
		WHERE
			(@categoryId IS NULL OR categoryId = @categoryId)
	ELSE
		SELECT
			CAST(0 AS MONEY) AS 'Budget',
			CAST(0 AS MONEY) AS 'Expense',
			CAST(0 AS MONEY) AS 'Encumbrance' ,
			CAST(0 AS MONEY) AS 'BalanceAvailable'

	-- d) Indirect Costs
	SELECT
		ISNULL(Budget,0) AS 'Budget',
		ISNULL(Expense,0) AS 'Expense',
		ISNULL(Encumbrance,0) AS 'Encumbrance',
		ISNULL(BalanceAvailable,0) AS 'BalanceAvailable'
	FROM @IndirectCostsTable

	-- e) Revenue
	SELECT ISNULL(Revenue,0) AS 'Revenue' FROM @RevenueTable

	-- f) Prior Year Balance
	SELECT ISNULL(PriorYearBalance,0) AS 'PriorYearBalance' FROM @PriorYearBalance

	--drop table #filteredFunds
	IF OBJECT_ID(N'tempdb..#AccessibleFunds', N'U') IS NOT NULL 
		DROP TABLE #AccessibleFunds
		
	IF OBJECT_ID(N'tempdb..#Account', N'U') IS NOT NULL 
		DROP TABLE #Account

	IF OBJECT_ID(N'tempdb..#AccountEnc', N'U') IS NOT NULL 
		DROP TABLE #AccountEnc

	SET NOCOUNT OFF
END




GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Altering [dbo].[GetCOISummaryXML]'
GO

/******************************************************************
* Name:						GetCOISummaryXML
* Purpose:					Generates the data required for the summary report in XML
*
* PARAMETERS
* Name    					Description					
* -------------  			-------------------------------------------
* @xmlListOfAdmPersonIds	Adm Person Ids
******************************************************************/

ALTER Procedure [dbo].[GetCOISummaryXML] (
		@xmlListOfAdmPersonIds TEXT,
		@supervisorName VARCHAR(100)
)
AS
BEGIN

	SET NOCOUNT ON
	
	declare @admPersonIds table (Sequence int identity, [ID] int) 
	
	declare @xmlDoc int        
	exec sp_xml_preparedocument @xmlDoc output, @xmlListOfAdmPersonIds
	insert into @admPersonIds select [Id] from openxml(@xmlDoc, '//IdList', 2) with (Id int)        
	exec sp_xml_removedocument @xmlDoc

	DECLARE @xml XML


	SET @xml = (SELECT  @supervisorName as SupervisorName, 
		(SELECT ltrim(rtrim(ADMP.LastName)) + ', ' + ltrim(rtrim(ADMP.FirstName)) as [Name], ADMP.Title, 
				IsNull(ADMP.OutsideMember, 0) as OutsideMember,  
				case COI.HasOutsideActivities when 1 then 'Y' when 0 then 'N' else '' end as HasOutsideActivities, 
				case COI.HasEquityInterests when 1 then 'Y' when 0 then 'N' else '' end as HasEquityInterests, 
				case COI.HasFamilyAssociations when 1 then 'Y' when 0 then 'N' else '' end as HasFamilyAssociations, 
				case COI.PolicyViolation when 1 then 'Y' when 0 then 'N' else '' end as PolicyViolation, 
				case COI.OtherActivity when 1 then 'Y' when 0 then 'N' else '' end as OtherActivity,
				convert(varchar, DateSubmitted, 101) as DateSubmitted,
				COI.Status as Status
		FROM @admPersonIds Ids
			INNER JOIN AdmPerson ADMP ON Ids.Id = ADMP.Id
			LEFT JOIN (
						SELECT * 
						FROM conflictofinterest
						WHERE Id in (
									SELECT Max(COI.Id) 
									FROM ConflictOfInterest COI
										INNER JOIN @admPersonIds AP ON COI.AdmPersonId = AP.Id
									GROUP BY AP.Id)
					) COI ON ADMP.Id = COI.AdmPersonId
		ORDER BY ADMP.LastName, ADMP.FirstName
		FOR XML PATH('COISummaryReport'),TYPE)
	FOR XML RAW('COISummaryReports'))

	SELECT @xml
	
END

GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Altering [dbo].[InjectPSDemogFeed]'
GO


/***************************************************************************
* Name:			InjectPSDemogFeed
* Purpose:		Using table Stg_IE_DemogFeed, inject new and changed agreement
*				demographic data.
*
* SCRAPED DATA		Coded
* -------------		-----
* Cost Center		
* Sponsor
* Fund
*
*
* AGREEMENT Tables Maintained
* Name									Coded	Operations					Done	
* -------------							-----	-------------------------	----
* AgrAgreement							I/U		Insert/Update				Y
* AgrBudgetContainer					I		Insert/Update				Y
* AgrBudgetContainerView				I		Insert/Update				Y
* AgrBudget								I		Insert/Update				Y
* SvcEntity_FwkDomainOrganization_Map			Insert/Update				Y
* AgrActivity									Insert/Update				Y
* SvcEntity								I		Insert						Y
* FwkResource							I		Insert						Y
* AnnAnnotationContainer				I		Insert						Y
* SvcEntity_AdmFacility_map						Insert/Update (Primary)		Y
* SvcEntity_AdmAdministrator_map				N/A
* SvcEntity_AdmStaffedPerson_map				Insert/Update (PI)			Y
*
* FUND Tables Maintained
* Name									Coded	Operations					Done	
* -------------							-----	-------------------------	----
* AgrFund										Insert/Update				Y
* SvcEntity										Insert						Y
* AgrFund_AgrAgreement_Map						Insert/Update				Y
* AgrCostCenter_AgrFund_Map						Insert/Update				Y
* AgrCostCenter									Insert						Y
* SvcEntity_AdmSponsor_map						Insert/Update				Y
* AdmSponsor									Insert/Update				Y
* 
* 
* 
* PARAMETERS
* Name				Description					
* -------------		-----------------------------------------------------------
* n/a
*
* ERRORS USED		Description
* -------------		-----------------------------------------------------
* n/a
*
* RETURN VALUE
* Value    			Description					
* --------------	------------------------------------------------------
* @_exitStatus		An exit status of either true or false
***************************************************************************/
ALTER PROCEDURE [dbo].[InjectPSDemogFeed]
AS
BEGIN

	SET NOCOUNT ON

	Begin Try

	begin transaction InjectPSDemogFeed

/*
  **************************************
  * S C R A P E D  D A T A             *
  **************************************
*/
	--NEW COST CENTERS
	SET IDENTITY_INSERT AgrCostCenter ON

	Insert into AgrCostCenter(
		Id
		,Number
		,DateCreated
		,AgrCostCenterSystemTypeId
	)
	Select s.AgrCostCenterId,s.Cost_center,getdate(), 
			case s.business_Unit when '1200' then 1 else 2 end as AgrCostCenterSystemTypeId
	FROM	Stg_IE_DemogFeed s
	WHERE	s.IsNewCostCenter = 1 and s.IsValid = 1

	SET IDENTITY_INSERT AgrCostCenter OFF

	--NEW SPONSORS
	SET IDENTITY_INSERT AdmSponsor ON

	Insert into AdmSponsor(
		Id,[Name],ShortName,Description,AdmSponsorTypeId,DateCreated,RexSponsorId)
	Select distinct s.AdmSponsorId,s.sponsor_name,left(s.sponsor_name,25),s.sponsor_name,IsNull(st.id,6)
		,getdate(), null
	FROM	Stg_IE_DemogFeed s
	left outer join AdmSponsorType st on st.PSCode = s.sponsor_code_id
	WHERE	s.IsNewSponsor = 1 and s.IsValid = 1

	SET IDENTITY_INSERT AdmSponsor OFF

/*
  **************************************
  * N E W  A G R E E M E N T S         *
  **************************************
*/
	-- NEW FwkResources
	SET IDENTITY_INSERT FwkResource ON

	INSERT	FwkResource (Id, FwkResourceTypeId)
	SELECT	DISTINCT s.FwkResourceId, 1
	FROM	Stg_IE_DemogFeed s
	WHERE	s.IsNewAgreement = 1 and s.IsValid = 1 and IsAgreementMaintained = 1

	SET IDENTITY_INSERT FwkResource OFF

	-- NEW SvcEntity
	SET IDENTITY_INSERT SvcEntity ON

	INSERT	SvcEntity (Id, SvcEntityTypeId, FwkResourceId)
	SELECT	DISTINCT s.SvcEntityId, 1, s.FwkResourceId
	FROM	Stg_IE_DemogFeed s
	WHERE	s.IsNewAgreement = 1 and s.IsValid = 1 and IsAgreementMaintained = 1

	SET IDENTITY_INSERT SvcEntity OFF

	-- NEW AgrBudgetContainer
	SET IDENTITY_INSERT AgrBudgetContainer ON

	INSERT			AgrBudgetContainer (Id, Name, Description, IndirectCostBaseId, AgrBudgetTemplateTypeId)
	SELECT DISTINCT s.AgrBudgetContainerId, 
					CAST(s.AgrAgreementID AS varchar) + ' ' + s.Folder_Number, 
					'Agreement Budget for Rex agreement Id ' + CAST(s.AgrAgreementID AS varchar), 
					coalesce((select p.finICBaseTypeId from FinPSICBaseType p 
								 where p.[id] = isNull(s.ic_base_int,0))
							 ,1/* Default to MTDC if nothing else */),
					1	-- hard-coded value for budget template type Id
	FROM			Stg_IE_DemogFeed s
	WHERE	s.IsNewAgreement = 1 and s.IsValid = 1 and s.IsCurrentFund = 1 and IsAgreementMaintained = 1

	SET IDENTITY_INSERT AgrBudgetContainer OFF

	--NEW AgrBudgetContainerView for awarded
	SET IDENTITY_INSERT AgrBudgetContainerView ON

	INSERT INTO AgrBudgetContainerView (Id,AgrBudgetContainerId, AgrBudgetViewTypeId, TargetPatientNumber
									, PerCapitaValue, InflationRate, CurrentGrantYear)
	SELECT s.AgrBudgetContainerViewId,s.AgrBudgetContainerId
					,3/*Awarded Budget View Type*/,0,0,0,1 
	FROM Stg_IE_DemogFeed s
	WHERE	s.IsValid = 1 and s.IsCurrentFund = 1 and IsAgreementMaintained = 1
			and (s.IsNewAgreement = 1 
				or (not exists(select 1 from AgrBudgetContainerView 
								where id = s.AgrBudgetContainerViewId)
					and s.AgrBudgetContainerViewId is not null))

	SET IDENTITY_INSERT AgrBudgetContainerView OFF

	-- NEW AnnAnnotationContainer
	SET IDENTITY_INSERT AnnAnnotationContainer ON

	INSERT	AnnAnnotationContainer (Id, SbsEntityTypeId)
	SELECT	distinct s.AnnAnnotationContainerId, 21
	FROM	Stg_IE_DemogFeed s
	WHERE	s.IsNewAgreement = 1 and s.IsValid = 1 and IsAgreementMaintained = 1

	SET IDENTITY_INSERT AnnAnnotationContainer OFF

/*
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	I N S E R T  A G R A G R E E M E N T
	Insert the agreement that is flagged as a new agreement based on its current fund.
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*/
	SET IDENTITY_INSERT AgrAgreement ON

	INSERT	AgrAgreement
			(
				Id,
				CurrentId,
				PIPersonId,
				AgrTransactionTypeId,
				AgrAgreementTypeId,
				AgrAgreementStatusTypeId,
				OverallStatus,
				FolderNumber,
				ParentFolderNumber,
				ShortTitle,
				Title,
				DocumentNumber,
				RexOwned,
				IsCurrent,
				IsAmendment,
				AgrBudgetContainerId,
				LegacyIdentifier,
				LegacySystemName,
				ReceivedDate,
				ProjectStartDate,
				ProjectEndDate,
				AgrNumberSchemeTypeId,
				Resubmission,
				Response,
				RFAID,
				RFATitle,
				InsertedDate,
				SvcEntityId,
				FwkResourceId,
				AnnAnnotationContainerId,
				DateLastModified
			)
	SELECT distinct	AgrAgreementId,
				AgrAgreementId,
				PI_AdmPersonId,
				AgrTransactionTypeId,
				AgrAgreementTypeId,
				AgrAgreementStatusTypeId,
				'Fully Executed/Awarded - Activated' as OverallStatus,
				Folder_Number,
				'' as ParentFolderNumber,
				description,
				long_description,
				1 as DocumentNumber,
				0 as RexOwned,
				1 as IsCurrent,
				0 as IsAmendment,
				AgrBudgetContainerId,
				0 as LegacyIdentifier,
				'' as LegacySystemName,
				dtEffective, --ReceivedDate,
				proj_start_date,
				proj_end_date,
				1 as MultipleGrantNumbering,
				0 as Resubmission,
				0 as  Response,
				0 as RFAID,
				'' as RFATitle,
				GetDate(),
				SvcEntityId,
				FwkResourceId,
				AnnAnnotationContainerId,
				getdate()
	FROM	Stg_IE_DemogFeed s
	WHERE	s.IsNewAgreement = 1 and s.IsValid = 1 and s.IsCurrentFund = 1 and IsAgreementMaintained = 1
	SET IDENTITY_INSERT AgrAgreement OFF

/*
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	I N S E R T  S V C E N T I T Y  F A C I L I T Y  M A P
	Insert the facility map for an agreement with no prior facility map row.
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*/
	INSERT	SvcEntity_AdmFacility_Map ( SvcEntityId, AdmFacilityId, AdmFacilityRelationshipTypeId, PercentActivity, DateCreated)
	SELECT	s.SvcEntityId, s.AdmFacilityId, 1 /* Primary AdmFacilityRelationshipTypeId */, 100 /*nPercentActivity*/, getdate()
	FROM	Stg_IE_DemogFeed s
	WHERE	s.svcEntityFacilityMapId is null and s.IsValid = 1 and s.IsCurrentFund = 1  and IsAgreementMaintained = 1
			and IsNull(s.AdmFacilityId,0)<>0
/*
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	I N S E R T  S V C E N T I T Y  O R G A N I Z A T I O N  M A P
	Insert the organization map for an agreement that has no organization map.
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*/
	Insert Into svcentity_fwkDomainOrganization_map(
		 SvcEntityId
		,fwkDomainOrganizationId
		,fwkOrganizationRelationshipTypeId
		,DateCreated
	)
	Select s.svcEntityId, s.fwkDomainOrganizationId, 1 /* primary org*/ , getdate()
	From Stg_IE_DemogFeed s where s.IsValid = 1 and s.IsCurrentFund = 1  and IsAgreementMaintained = 1
		AND not exists(Select 1 from svcentity_fwkDomainOrganization_map om 
						where om.svcEntityId = s.svcEntityId and om.fwkOrganizationRelationshipTypeId = 1)
/*
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	I N S E R T  A C T I V I T Y
	Insert the AgrActivity table for a new agreement.
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*/
	Insert Into AgrActivity(
		 AgrAgreementId
		,AgrActivityTypeid
		,ActivityType
		,ActivitySubType
		,ActivitySubSubType
		,SequenceNo
	)
	Select s.AgrAgreementId, s.AgrActivityTypeid,'','','',0
	From Stg_IE_DemogFeed s where s.IsValid = 1  and s.IsCurrentFund = 1  and IsAgreementMaintained = 1
		AND not exists(Select 1 from AgrActivity ac 
						where ac.AgrAgreementId = s.AgrAgreementId)
/*
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	I N S E R T  S V C E N T I T Y  S T A F F E D  P I  P E R S O N  
	Insert the PI into the SvcEntity_StaffedPerson_Map table for a new agreement.
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*/
	Insert Into SvcEntity_AdmStaffedPerson_Map(
		 SvcEntityId
		,AdmPersonId
		,AdmStaffedPersonTypeId
		,DateCreated
	)
	Select s.svcEntityId, s.PI_AdmPersonId, 1 /* PI*/ , getdate()
	From Stg_IE_DemogFeed s where s.IsValid = 1 and s.IsCurrentFund = 1 and IsAgreementMaintained = 1
		AND not exists(Select 1 from SvcEntity_AdmStaffedPerson_Map spm 
						where spm.svcEntityId = s.svcEntityId and AdmStaffedPersonTypeId = 1)
/*
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	I N S E R T  S V C E N T I T Y  A D M S P O N S O R 
	Insert the Sponsor into the SvcEntity_AdmSponsor_Map table for a new agreement.
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*/
	Insert Into SvcEntity_AdmSponsor_Map(
		 SvcEntityId
		,AdmSponsorId
		,AdmSponsorRelationTypeId
		,SponsorNumber
		,DateCreated
		,CFDANumber
	)
	Select s.svcEntityId, s.AdmSponsorId, 1 as AdmSponsorRelationTypeId,
		sponsor_agree_id_format, getdate() as DateCreated ,CFDA_number
	From Stg_IE_DemogFeed s where s.IsValid = 1 and s.IsCurrentFund = 1 and s.IsAgreementMaintained = 1
		AND not exists(Select 1 from SvcEntity_AdmSponsor_Map spm 
						where spm.svcEntityId = s.svcEntityId and AdmSponsorRelationTypeId = 1)
/*
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	I N S E R T  S V C E N T I T Y  F O R  N E W  F U N D S 
	Insert the service entity for new funds.
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*/
	SET IDENTITY_INSERT SvcEntity ON

	INSERT	SvcEntity (Id, SvcEntityTypeId, FwkResourceId)
	SELECT	s.AgrFundSvcEntityId, 3, s.FwkResourceId
	FROM	Stg_IE_DemogFeed s
	WHERE	s.IsNewFund = 1 and s.IsValid = 1  and AgrAgreementId is not null

	SET IDENTITY_INSERT SvcEntity OFF
/*
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	I N S E R T  A G R F U N D  
	Insert the fund into the AgrFund table for a new fund.
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*/
	SET IDENTITY_INSERT AgrFund ON

	INSERT		AgrFund (
					Id, SvcEntityId, FinAccountCycleTypeId, FundNumber, AgrFundStatusTypeId, 
					AgrFundAwardTypeId, AgrFundOverheadClassificationId, CFDA, 
					DocumentLetter, FundShortTitle, FundTitle, BusinessUnitId, RexOwned, 
					ActivationDate, EffectiveDate, AgrFundTypeId, AgrFundSubTypeId, ManagerId
					)
	SELECT			s.AgrFundId, s.SvcEntityId, s.FinAccountCycleTypeId, s.project_grant, s.AgrFundStatusTypeId, 
					s.AgrFundAwardTypeId, s.AgrFundOverheadClassificationId, s.cfda_number, 
					s.doc_letter, left(s.Description,50), left(s.long_Description,128), s.BusinessUnitId, 
					case IsNull(ltrim(rtrim(s.folder_number)),'') when '' then 0 else 1 end as RexOwned, 
					s.ActivationDate, s.Effective_Date, 1, s.AgrFundSubTypeId, s.PI_AdmPersonId
	FROM		Stg_IE_DemogFeed s
	WHERE		s.IsNewFund = 1 and s.IsValid = 1 and AgrAgreementId is not null

	SET IDENTITY_INSERT AgrFund OFF

/*
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	I N S E R T  A G R F U N D _ A G R A G R E E M E N T _ M A P  
	Insert the fund into the AgrFund_AgrAgreement_Map table for a new agreement.
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*/
	SET IDENTITY_INSERT AgrFund_AgrAgreement_Map ON

	INSERT	AgrFund_AgrAgreement_Map (
				Id, AgrFundId, AgrAgreementId, SvcEntityId, FinAccountCycleTypeId, FundNumber, 
				AgrFundStatusTypeId, AgrFundAwardTypeId, AgrFundOverheadClassificationId, 
				CFDA, DocumentLetter, FundShortTitle, FundTitle, EffectiveDate, 
				BusinessUnitId, RexOwned, ActivationDate, AgrFundTypeId, AgrFundSubTypeId, ManagerId
				)
	SELECT		AgrFundAgreementMapId, AgrFundId, AgrAgreementId, SvcEntityId, FinAccountCycleTypeId, project_grant, 
				AgrFundStatusTypeId, AgrFundAwardTypeId, AgrFundOverheadClassificationId, 
				cfda_number, doc_letter, left(Description,50), left(Long_Description,128), Effective_Date, 
				BusinessUnitId, case IsNull(ltrim(rtrim(folder_number)),'') when '' then 0 else 1 end
					as RexOwned, ActivationDate, 1, AgrFundSubTypeId, PI_AdmPersonId
	FROM	Stg_IE_DemogFeed 
	WHERE	IsValid = 1 and AgrFundAgreementMapId is not null and AgrAgreementId is not null
			and not exists(Select 1 from AgrFund_AgrAgreement_Map fm 
							where fm.id = Stg_IE_DemogFeed.AgrFundAgreementMapId)

	SET IDENTITY_INSERT AgrFund_AgrAgreement_Map OFF

/*
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	I N S E R T  A G R B U D G E T  
	Insert the budget if this is a maintained agreement and there was no container view
	or this is a new agreement.
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*/
	SET IDENTITY_INSERT AgrBudget ON

	INSERT INTO AgrBudget (Id,AgrBudgetContainerViewId, AgrBudgetTypeId, StartDate, EndDate
							,[Year], IsAwarded, AgrFundAgreeMapId, IsAdjustment)
	SELECT DISTINCT s.AgrBudgetId,s.AgrBudgetContainerViewId,1/*Annual Budget Type*/
					,coalesce(s.dtBudgetStart,s.dtprojectstart,'1/1/1900')
					,coalesce(s.dtBudgetEnd,s.dtprojectend,'12/31/2099')
					,1,1,s.AgrFundAgreementMapId,0 
	FROM Stg_IE_DemogFeed s
	WHERE	s.IsValid = 1 and s.agrBudgetId is not null  and IsAgreementMaintained = 1 
			and not exists(select 1 from AgrBudget where id = s.AgrBudgetId)

	SET IDENTITY_INSERT AgrBudget OFF


/*
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	I N S E R T  A G R B U D G E T  I T E M
	--NEW AgrBudgetItem for awarded for only new agreements that are maintained by this feed.
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*/
	INSERT INTO AgrBudgetItem (AgrBudgetId, AgrContainerAccountTemplateMapId, ItemValue)
	SELECT s.AgrBudgetId,tm.Id,0 
	FROM Stg_IE_DemogFeed s
	inner join AgrBudgetItem_containerAccount_Template_map tm on tm.AgrContainerTemplateId = 1
					and tm.AgrAccountTemplateId = (select min(tm1.AgrAccountTemplateId) from AgrBudgetItem_containerAccount_Template_map tm1
													where tm1.AgrContainerTemplateId = 1)
	WHERE	s.IsValid = 1 
			and s.agrBudgetId is not null  and IsAgreementMaintained = 1
			and not exists(select 1 from AgrBudgetItem
								where AgrBudgetId = s.AgrBudgetId 
									and agrContainerAccountTemplateMapId = tm.Id)

/*
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	I N S E R T  A G R B U D G E T  I C  R A T E
	Insert the budget if this is a maintained agreement and there was no container view
	or this is a new agreement.
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*/
INSERT INTO AgrBudgetICRate (AgrBudgetId,Rate,NumberOfMonths,SequenceNo,EffectiveDate)
	SELECT DISTINCT s.AgrBudgetId,s.indirect_cost_rate,12,1,null
	FROM Stg_IE_DemogFeed s
	WHERE	s.IsValid = 1
			and s.agrBudgetId is not null  and IsAgreementMaintained = 1
			and not exists(select 1 from AgrBudgetICRate where AgrBudgetId = s.AgrBudgetId)
/*
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	I N S E R T  A G R C O S T C E N T E R _ A G R F U N D _ M A P  
	Insert the fund into the AgrCostCenter_AgrFund_Map table for a new agreement.
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*/
	INSERT	AgrCostCenter_AgrFund_Map
				(AgrFundAgreementMapId, AgrCostCenterId, DateCreated, AgrCostCenterStatusTypeId)
	SELECT	AgrFundAgreementMapId, AgrCostCenterId, GetDate(), AgrCostCenterStatusTypeId
	FROM	Stg_IE_DemogFeed 
	WHERE	IsValid = 1 and AgrFundAgreementMapId is not null and AgrAgreementId is not null
			and AgrCostCenterId is not null
			and not exists(Select 1 from AgrCostCenter_AgrFund_Map cm 
							where cm.AgrFundAgreementMapId = Stg_IE_DemogFeed.AgrFundAgreementMapId)


/*
  **************************************
  * C H A N G E D  A G R E E M E N T S *
  **************************************
*/

/*
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	U P D A T E   A G R A G R E E M E N T
	Change the data on the TOP DOC of the main agreement.
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*/
	Update	a
	Set
		PIPersonId = s.PI_AdmPersonId,
		AgrTransactionTypeId = s.AgrTransactionTypeId,
		AgrAgreementTypeId = s.AgrAgreementTypeId,
		AgrAgreementStatusTypeId = s.AgrAgreementStatusTypeId,
		OverallStatus = 'Fully Executed/Awarded - Activated',
		ShortTitle = s.description,
		Title = s.long_description,
		IsCurrent = 1,
		IsAmendment = 0,
		ProjectStartDate = s.dtProjectStart,
		ProjectEndDate = s.dtProjectEnd,
		DateLastModified = GetDate()
	FROM	Stg_IE_DemogFeed s
	INNER JOIN AgrAgreement a on a.Id = s.AgrAgreementId 
	where s.IsNewAgreement = 0 and s.IsValid = 1 and s.IsChanged = 1 and s.IsCurrentFund = 1
		and s.IsAgreementMaintained = 1
/*
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	U P D A T E   I C  B A S I S  O N  B U D G E T  C O N T A I N E R  F O R  A G R E E M E N T
	The only reason to ever update a budget container is if the IC basis code changes.
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*/
	UPDATE bc 
	SET IndirectCostBaseId = case s.ic_base_int	
								when 0 Then 6 -- Lump Sum
								when 1 then 3 -- TDC (0% & up)
								when 2 then 5 -- S & W
								when 3 then 1 -- MTDC
								when 6 then 1 -- MTDC
								when 8 then 2 -- TADC (T32 Training Only)
								when 9 then 7 -- Inactivate O.H.
								when 10 then 1 -- MTDC
								when 11 then 1 -- MTDC
								when 12 then 1 -- MTDC
								when 13 then 2 -- TADC (T32 Training Only)
								when 14 then 5 -- S & W
								when 15 then 3 -- TDC (0% & up)
								else 1 -- MTDC
							end
	FROM Stg_IE_DemogFeed s INNER JOIN AgrBudgetContainer bc on bc.id = s.AgrBudgetContainerId
	where s.IsNewAgreement = 0 and s.IsValid = 1 and s.IsChanged = 1 and s.IsCurrentFund = 1
		and s.IsAgreementMaintained = 1

/*
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	U P D A T E  S V C E N T I T Y  O R G A N I Z A T I O N  M A P
	Update the svcentity organization map if there is a change.
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*/
	Update sfm
	Set fwkDomainOrganizationId = s.fwkDomainOrganizationId
	From Stg_IE_DemogFeed s INNER JOIN svcentity_fwkDomainOrganization_map sfm 
						  on s.svcentityId = sfm.svcentityId and sfm.fwkorganizationRelationshipTypeId = 1 -- primary
	where s.IsNewAgreement = 0 and s.IsValid = 1 and s.IsCurrentFund = 1 and s.IsChanged = 1 
			and s.Orig_fwkDomainOrganizationId <> s.fwkDomainOrganizationId
			and s.IsAgreementMaintained = 1

/*
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	U P D A T E  A G R  A C T I V I T Y
	Update the AgrActivity table if there is a change.
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*/
	Update ac
	Set AgrActivityTypeId = s.AgrActivityTypeId
	From Stg_IE_DemogFeed s INNER JOIN AgrActivity ac on s.AgrAgreementId = ac.AgrAgreementId
	where s.IsNewAgreement = 0 and s.IsValid = 1 and s.IsCurrentFund = 1 and s.IsChanged = 1 
		and s.Orig_AgrActivityTypeId <> s.AgrActivityTypeId
		and s.IsAgreementMaintained = 1

/*
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	U P D A T E  S V C E N T I T Y  F A C I L I T Y  M A P
	Update the facility map table if any changes.
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*/
	Update sfm
	Set AdmFacilityId = s.AdmFacilityId
		,DateCreated = getdate()
	From Stg_IE_DemogFeed s INNER JOIN SvcEntity_AdmFacility_Map sfm 
						  on s.svcentityId = sfm.svcentityId and sfm.AdmFacilityRelationshipTypeId = 1 -- primary
	where s.IsNewAgreement = 0 and s.IsValid = 1 and s.IsChanged = 1 and s.IsCurrentFund = 1
		 and s.Orig_AdmFacilityId <> s.AdmFacilityId and IsNull(s.admFacilityId,0)<>0
		and s.IsAgreementMaintained = 1

/*
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	U P D A T E  T H E  P I  I N  S T A F F E D  P E R S O N  M A P  
	Update the PI in the staffed person map table if any changes in PI.  We don't get any other
	staff in the PS demog feed.
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*/
	Update sfm
	Set AdmPersonId = s.PI_AdmPersonId
		,DateCreated = getdate()
	From Stg_IE_DemogFeed s INNER JOIN SvcEntity_AdmStaffedPerson_Map sfm 
						  on s.svcentityId = sfm.svcentityId and sfm.AdmStaffedPersonTypeId = 1 -- PI
	where s.IsNewAgreement = 0 and s.IsValid = 1 and s.IsChanged = 1 and s.IsCurrentFund = 1 
		and s.Orig_PI_AdmPersonId <> s.PI_AdmPersonId
		and s.IsAgreementMaintained = 1

/*
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	U P D A T E  A D M S P O N S O R 
	Update the Sponsor for an agreement.
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	Update spsr
		Set [Name] = s.sponsor_name
			,ShortName =Left(s.sponsor_name,25)
			,Description = s.sponsor_name
			,AdmSponsorTypeId = IsNull(st.id,6)
			,DateCreated = getdate()
	FROM	Stg_IE_DemogFeed s inner join admSponsor spsr on spsr.Id = s.AdmSponsorId
	left outer join AdmSponsorType st on st.pscode = s.sponsor_code_id
	WHERE	s.IsNewSponsor = 0 and s.IsValid = 1 and s.IsChanged = 1 and s.IsCurrentFund = 1
			and s.IsAgreementMaintained = 1 and s.sponsor_name <> 'SUNDRY'
*/

/*
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	U P D A T E  S V C E N T I T Y  A D M S P O N S O R 
	Update the Sponsor into the SvcEntity_AdmSponsor_Map table for a new agreement.
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*/
	Update sm 
	Set  
		 AdmSponsorId = s.AdmSponsorId
		,AdmSponsorRelationTypeId = 1
		,SponsorNumber = s.sponsor_agree_id_format
		,DateCreated = getdate()
		,CFDANumber = s.CFDA_number
	From Stg_IE_DemogFeed s 
	inner join SvcEntity_AdmSponsor_Map sm on sm.SvcEntityId = s.SvcEntityId
				and AdmSponsorRelationTypeId = 1
	where s.IsNewAgreement = 0 and s.IsChanged = 1 and s.IsValid = 1 and s.IsCurrentFund = 1
			and s.IsAgreementMaintained = 1

/*
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	U P D A T E  A G R F U N D  
	Update the fund into the AgrFund table for a new agreement.
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*/
	UPDATE f
	SET
		FinAccountCycleTypeId				= s.FinAccountCycleTypeId
		,AgrFundStatusTypeId				= s.AgrFundStatusTypeId
		,AgrFundAwardTypeId					= s.AgrFundAwardTypeId
		,AgrFundOverheadClassificationId	= s.AgrFundOverheadClassificationId
		,CFDA								= s.cfda_number
		,DocumentLetter						= s.doc_letter
		,FundShortTitle						= left(s.Description,50)
		,FundTitle							= left(s.long_Description,128)
		,BusinessUnitId						= s.BusinessUnitId
		,RexOwned							= case IsNull(ltrim(rtrim(s.folder_number)),'') when '' then 0 else 1 end
		,EffectiveDate						= s.Effective_Date
		,ActivationDate						= s.ActivationDate
		,AgrFundTypeId						= 1
		,AgrFundSubTypeId					= s.AgrFundSubTypeId
		,ManagerId							= s.PI_AdmPersonId
	FROM		Stg_IE_DemogFeed s
	INNER JOIN	AgrFund f on f.Id = s.AgrFundId
	WHERE		s.IsNewFund = 0 and s.IsValid = 1 

/*
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	U P D A T E  A G R F U N D _ A G R A G R E E M E N T _ M A P  
	Update the fund into the AgrFund_AgrAgreement_Map table for an agreement.
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*/
	UPDATE	f 
	SET			
		AgrFundId							= s.AgrFundId
		, AgrAgreementId					= s.AgrAgreementId
		, SvcEntityId						= s.SvcEntityId
		, FinAccountCycleTypeId				= s.FinAccountCycleTypeId
		, FundNumber						= s.project_grant
		, AgrFundStatusTypeId				= s.AgrFundStatusTypeId
		, AgrFundAwardTypeId				= s.AgrFundAwardTypeId
		, AgrFundOverheadClassificationId	= s.AgrFundOverheadClassificationId
		, CFDA								= s.cfda_number
		, DocumentLetter					= s.doc_letter
		, FundShortTitle					= left(s.Description,50)
		, FundTitle							= left(s.Long_Description,128)
		, EffectiveDate						= s.Effective_Date
		, ActivationDate					= s.ActivationDate
		, BusinessUnitId					= s.BusinessUnitId
		, RexOwned							= case IsNull(ltrim(rtrim(s.folder_number)),'') when '' then 0 else 1 end
		, AgrFundTypeId						= 1
		, AgrFundSubTypeId					= s.AgrFundSubTypeId
		, ManagerId							= s.PI_AdmPersonId
	FROM		Stg_IE_DemogFeed s
	INNER JOIN	AgrFund_AgrAgreement_Map f on f.Id = s.AgrFundAgreementMapId
	WHERE		s.IsNewFund = 0 and s.IsValid = 1 and s.agragreementid is not null

/*
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	U P D A T E  A G R B U D G E T  
	Update the budget if this is a maintained agreement.
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*/
	UPDATE b
	SET
		startDate = coalesce(s.dtBudgetStart,s.dtprojectstart,'1/1/1900')
		,EndDate = coalesce(s.dtBudgetEnd,s.dtprojectend,'12/31/2099')
		,AgrFundAgreeMapId = s.AgrFundAgreementMapId
	FROM Stg_IE_DemogFeed s
	INNER JOIN AgrBudget b on b.id = s.agrBudgetId
	WHERE	s.IsValid = 1  and s.AgrFundAgreementMapId is not null and s.IsAgreementMaintained = 1

/*
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	U P D A T E  A G R B U D G E T  I C  R A T E
	Update the budget IC Rate if this is a maintained agreement.
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*/
	UPDATE b
	SET Rate = s.indirect_cost_rate
	FROM Stg_IE_DemogFeed s
	INNER JOIN AgrBudgetICRate b on b.agrBudgetid = s.agrBudgetId
	WHERE	s.IsValid = 1 and s.IsAgreementMaintained = 1
/*
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	U P D A T E  A G R C O S T C E N T E R _ A G R F U N D _ M A P  
	Update the cost center and status into the AgrCostCenter_AgrFund_Map table for an agreement.
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*/
	UPDATE cm
	SET	 AgrCostCenterId = s.AgrCostCenterId
		,AgrCostCenterStatusTypeId = s.AgrCostCenterStatusTypeId
		,DateCreated = getdate()
	FROM 
		Stg_IE_DemogFeed s 
	INNER JOIN 
		AgrCostCenter_AgrFund_Map cm 
	ON
		cm.AgrFundAgreementMapId = s.AgrFundAgreementMapId
		and cm.AgrCostCenterId = s.Orig_AgrCostCenterId
	WHERE
		s.IsNewCostCenter = 0 and s.IsValid = 1 and s.AgrFundAgreementMapId is not null
		and s.AgrCostCenterId is not null and s.agragreementid is not null

	commit transaction InjectPSDemogFeed

	End Try

    BEGIN CATCH
    DECLARE 
        @ErrorMessage    NVARCHAR(4000),
        @ErrorNumber     INT,
        @ErrorSeverity   INT,
        @ErrorState      INT,
        @ErrorLine       INT,
        @ErrorProcedure  NVARCHAR(200);

    -- Assign variables to error-handling functions that 
    -- capture information for RAISERROR.
    SELECT 
        @ErrorNumber = ERROR_NUMBER(),
        @ErrorSeverity = ERROR_SEVERITY(),
        @ErrorState = ERROR_STATE(),
        @ErrorLine = ERROR_LINE(),
        @ErrorProcedure = ISNULL(ERROR_PROCEDURE(), '-');

    -- Building the message string that will contain original
    -- error information.
    SELECT @ErrorMessage = 
        N'Error %d, Level %d, State %d, Procedure %s, Line %d, ' + 
            'Message: '+ ERROR_MESSAGE();

	IF XACT_STATE() <> 0 Rollback transaction InjectPSDemogFeed

    -- Raise an error: msg_str parameter of RAISERROR will contain
    -- the original error information.
    RAISERROR 
        (
        @ErrorMessage, 
        @ErrorSeverity, 
        1,               
        @ErrorNumber,    -- parameter: original error number.
        @ErrorSeverity,  -- parameter: original error severity.
        @ErrorState,     -- parameter: original error state.
        @ErrorProcedure, -- parameter: original error procedure name.
        @ErrorLine       -- parameter: original error line number.
        );
		return 99
    END CATCH;
END


GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Altering [dbo].[MapAgreementChangesFromInfoEd]'
GO



/***************************************************************************
* Name:			MapAgreementChangesFromInfoEd
* Purpose:		Updates the Insight Agreement data with changes from InfoEd.
*
***************************************************************************/
ALTER PROCEDURE dbo.MapAgreementChangesFromInfoEd
AS
BEGIN

	SET NOCOUNT ON

	BEGIN
		BEGIN TRY
		BEGIN TRANSACTION UpdateAgreementsFromInfoEd
		-- PIPerson
		Update AgrAgreement Set PIPersonId = Stg.PIPersonId
			From Stg_IE_AgrAgreement Stg
			Where AgrAgreement.Id = Stg.AgrAgreementId AND
				AgrAgreement.PIPersonId != Stg.PIPersonId
		
		Update AgrAgreement Set ProjectStartDate = Stg.ProjectStartDate
			From Stg_IE_AgrAgreement Stg
			Where AgrAgreement.Id = Stg.AgrAgreementId AND ISNULL(AgrAgreement.ProjectStartDate, '') != ISNULL(Stg.ProjectStartDate, '')
		
		Update AgrAgreement Set ProjectEndDate = Stg.ProjectEndDate
			From Stg_IE_AgrAgreement Stg
			Where AgrAgreement.Id = Stg.AgrAgreementId AND ISNULL(AgrAgreement.ProjectEndDate, '') != ISNULL(Stg.ProjectEndDate, '')
		
		Update AgrAgreement Set Title = Stg.AgreementTitle
			From Stg_IE_AgrAgreement Stg
			Where AgrAgreement.Id = Stg.AgrAgreementId AND CAST(AgrAgreement.Title as Varchar(4000)) != Stg.AgreementTitle
		
		Update AgrAgreement Set ShortTitle = Stg.AgreementShortTitle
			From Stg_IE_AgrAgreement Stg
			Where AgrAgreement.Id = Stg.AgrAgreementId AND AgrAgreement.ShortTitle != Stg.AgreementShortTitle
		
		Update AgrAgreement Set ReceivedDate = Stg.ReceivedDate
			From Stg_IE_AgrAgreement Stg
			Where AgrAgreement.Id = Stg.AgrAgreementId AND ISNULL(AgrAgreement.ReceivedDate, '') != ISNULL(Stg.ReceivedDate, '')

		Update AgrAgreement Set LegacyIdentifier = Stg.LegacyIdentifier
			From Stg_IE_AgrAgreement Stg
			Where AgrAgreement.Id = Stg.AgrAgreementId AND ISNULL(AgrAgreement.LegacyIdentifier, '') != ISNULL(Stg.LegacyIdentifier, '')

		Update AgrAgreement Set ParentFolderNumber = Stg.ParentFolderNumber
			From Stg_IE_AgrAgreement Stg
			Where AgrAgreement.Id = Stg.AgrAgreementId AND ISNULL(AgrAgreement.ParentFolderNumber, '') != ISNULL(Stg.ParentFolderNumber, '') 
		
		Update AgrAgreement Set RFAID = Stg.RFAID
			From Stg_IE_AgrAgreement Stg
			Where AgrAgreement.Id = Stg.AgrAgreementId AND ISNULL(AgrAgreement.RFAID, '') != ISNULL(Stg.RFAID, '')

		Update AgrAgreement Set RFATitle = Stg.RFATitle
			From Stg_IE_AgrAgreement Stg
			Where AgrAgreement.Id = Stg.AgrAgreementId AND ISNULL(AgrAgreement.RFATitle, '')!= ISNULL(Stg.RFATitle, '')

		Update AgrAgreement Set AgrAgreementStatusTypeId = Stg.AgrAgreementStatusTypeId
			From Stg_IE_AgrAgreement Stg
			Where AgrAgreement.Id = Stg.AgrAgreementId 

		UPDATE SvcEntity_AdmSponsor_Map SET AdmSponsorId = Stg.AdmSponsorId
			FROM Stg_IE_AgrAgreement Stg
			WHERE SvcEntity_AdmSponsor_Map.SvcEntityId = Stg.SvcEntityId
				AND		SvcEntity_AdmSponsor_Map.AdmSponsorId != Stg.AdmSponsorId
				AND AdmSponsorRelationTypeId = 1

		UPDATE 	SvcEntity_AdmSponsor_Map SET SponsorNumber = Stg.SponsorNumber	
				FROM Stg_IE_AgrAgreement Stg
				inner join AgrAGreement A
					on Stg.Prop_No = A.PropNumber
				inner join SvcEntity_AdmSponsor_Map SM
					on SM.SVcEntityId = A.SvcEntityId

--		Update AgrAgreement Set AdmSponsorId = Stg.AdmSponsorId
--			From Stg_IE_AgrAgreement Stg
--			Where AgrAgreement.Id = Stg.AgrAgreementId 

		Update AgrAgreement Set PIPersonId = Stg.PIPersonId
			From Stg_IE_AgrAgreement Stg
			Where AgrAgreement.Id = Stg.AgrAgreementId --AND AgrAgreement.PIPersonId != Stg.PIPersonId

		UPDATE AgrAgreement Set IsCurrent = Stg.IsCurrent
			From Stg_IE_AgrAgreement Stg
			Where AgrAgreement.Id = Stg.AgrAgreementId
			and AgrAgreement.IsCurrent <> Stg.IsCurrent
		
		-- Activity Type ID
		Update AgrActivity SET AgrActivityTypeId = Stg.AgrActivityTypeID
			From Stg_IE_AgrAgreement Stg
			Where AgrActivity.AgrAgreementId = Stg.AgrAgreementId 
				and Stg.AgrActivityTypeID IS NOT NULL

		-- SUB Type
		Update AgrActivity SET ActivitySubType = Stg.SubActivityType 
			From Stg_IE_AgrAgreement Stg
			Where AgrActivity.AgrAgreementId = Stg.AgrAgreementId 
		
		-- Activity Type Text field
		Update AgrActivity Set ActivityType = Stg.Description
			FROM AgrActivityType Stg
			WHERE Stg.Id = AgrActivity.AgrActivityTypeId

		-- ACtivity Type PSDescription from Research Finance
		UPDATE AgrActivity SET PSDescription = Stg.ActTypePSDescription 
			FROM Stg_IE_AgrAgreement STg
			WHERE AgrActivity.AgrAGreementId = Stg.AgrAgreementID
			AND ISNULL(Stg.ActTypePSDescription, '') != ISNULL(AgrActivity.PSDescription, '')
			AND Stg.ActTypePSDescription IS NOT NULL


--		-- ONE TIME UPDATE		
--		Update AgrAgreement Set PropNumber = Stg.Prop_No
--			From Stg_IE_AgrAgreement Stg
--			Where AgrAgreement.Id = Stg.AgrAgreementId AND ISNULL(AgrAgreement.PropNumber, '') != Stg.Prop_No
--		

	----------------------------------------------------------------------
	-- COMMIT THE TRANSACTION!!!
	-- And end the try block, then handle any errors.
	----------------------------------------------------------------------
	COMMIT TRANSACTION UpdateAgreementsFromInfoEd
	END TRY

	BEGIN CATCH
		DECLARE 
			@ErrorMessage    NVARCHAR(4000),
			@ErrorNumber     INT,
			@ErrorSeverity   INT,
			@ErrorState      INT,
			@ErrorLine       INT,
			@ErrorProcedure  NVARCHAR(200);

		-- Assign variables to error-handling functions that 
		-- capture information for RAISERROR.
		SELECT 
			@ErrorNumber = ERROR_NUMBER(),
			@ErrorSeverity = ERROR_SEVERITY(),
			@ErrorState = ERROR_STATE(),
			@ErrorLine = ERROR_LINE(),
			@ErrorProcedure = ISNULL(ERROR_PROCEDURE(), '-');

		-- Building the message string that will contain original
		-- error information.
		SELECT @ErrorMessage = 
			N'Error %d, Level %d, State %d, Procedure %s, Line %d, ' + 
				'Message: '+ ERROR_MESSAGE();
	
		-----------------------------------------------------
		-- ROLLBACK the transaction if we got here....
		-----------------------------------------------------
		IF XACT_STATE() <> 0 Rollback transaction UpdateAgreementsFromInfoEd

		-- Raise an error: msg_str parameter of RAISERROR will contain
		-- the original error information.
		RAISERROR 
			(
			@ErrorMessage, 
			@ErrorSeverity, 
			1,               
			@ErrorNumber,    -- parameter: original error number.
			@ErrorSeverity,  -- parameter: original error severity.
			@ErrorState,     -- parameter: original error state.
			@ErrorProcedure, -- parameter: original error procedure name.
			@ErrorLine       -- parameter: original error line number.
			);
			return 99
		END CATCH;

	END
		
	SET NOCOUNT OFF

END



GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Altering [dbo].[MapInfoEdSponsorCodes]'
GO



/***************************************************************************
* Name:			MapInfoEdSponsorCodes
* Purpose:		Updates the InfoEdSponsorCode column of the AdmSponsor table
*
***************************************************************************/
ALTER PROCEDURE dbo.MapInfoEdSponsorCodes
AS
BEGIN

	SET NOCOUNT ON
--
--	Update AdmSponsor Set InfoEdSponCode = Stg.Spon_Code
--		From Stg_IE_Sponsors Stg
--		where Stg.nSponsorId = AdmSponsor.RexSponsorId
--
--	-- Match on Name.
--	update AdmSponsor set InfoEdSponCode = Sub.Spon_Code
--		from (select Stg.Spon_Code, S.Id as AdmSponsorId from Stg_IE_Sponsors Stg
--		inner join AdmSponsor S on Stg.sName = S.[Name]
--		Where S.InfoEdSponCode is null) Sub
--		where Sub.AdmSponsorId = AdmSponsor.Id
--		
	SET NOCOUNT OFF

END



GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Creating [dbo].[GetPendingItemIds]'
GO
/************************************************************************************************          
* Name:  GetPendingItemIds                                                            
* Purpose: Stored procedure for retrieving the set of pending items(protocolProcess Ids with status of          
*  'Pending', 'Deferred', 'Hold', 'Req. Mod.') on Protocols that have status of          
*  'Active', 'Hold', or 'Hold-Lapsed'          
*             
*  This also returns processes that are pending (have status of pending); this means          
*  they have been submitted to Rex, but have not returned from Rex          
*          
* PARAMETERS            
* Name   Description          
* ------------------------- -----------------------------          
* @domainuserid   FwkDomainUserId of the user whose pending items we want to retrieve      
* @module    - module instantiating the page ('H'-Humans, 'A'-Animals)      
* @protocolNo    -Protocol number(Search Criteria)                        
* @protocolTitle   -Protocol Title (Serach criteria)                        
* @sponsorName    -Spnosor name (Search criteria)                        
* @versionNo    -Verson number (Sercah criteria)                        
* @expDateFrom DateTime  -expiry Date From (Search Criteria)                        
* @expDateTo    -Expiry Date To (Search Criteria)                        
* @piId      -PI Id (Search criteria)                        
* @cosIds     -CosIds (Serach Criteria)                        
* @sortColumn    -SortColumn(SubmissionDate-Default)                  
* @sortOrder    -Sort Order for the result set (bit=1-->Desc,0-->Ascending)                      
************************************************************************************************/          
          
CREATE procedure [dbo].[GetPendingItemIds] --103100 ,'H' ,'2007'      
(          
 @domainuserid int,      
 @module char(1),      
 @protocolNo varchar(12)= null,                        
 @protocolTitle varchar(1024)= null,                        
 @sponsorName varchar(75)= null,                        
 @versionNo varchar(100)= null,                        
 @expDateFrom DateTime = null,                        
 @expDateTo DateTime = null,                        
 @piId Int=null,                        
 @cosIds varchar(Max)= null,  
 @species VarChar(max)= null ,  
 @isRadioIsotope bit = null ,  
 @isBiologicalAgent bit = null ,  
 @isToxicChemicals bit = null ,  
 @isTissueTest bit = null ,                       
 @sortColumn varchar(150)= 'SubmissionDate',                                              
 @sortOrder bit=0-->Asc,0-->Desc                                       
)          
as          
begin          
set nocount on          
          
 if  @protocolNo is  null                      
 Set @protocolNo = '%'                      
else                      
 Set @protocolNo = @protocolNo + '%'                      
                      
if  @protocolTitle is null                      
 Set @protocolTitle = '%'                      
else                      
 Set @protocolTitle = @protocolTitle + '%'                      
                      
if @sponsorName is null                      
 Set @sponsorName = '%'                      
Else                       
 Set @sponsorName = @sponsorName + '%'          
    
if @versionNo is null                      
 Set @versionNo =  '%'                      
Else                       
 Set @versionNo = @versionNo + '%'       
                               
-- constants          
declare @protocolResourceType int          
set @protocolResourceType = 2          
          
declare @keyGiverAccessLevel int          
set @keyGiverAccessLevel = 2          
          
declare @pendingProcessStatus varchar(256)          
set @pendingProcessStatus = 'PPSTATUS_PEND'          
          
declare @submittedProcessStatus varchar(256)          
set @submittedProcessStatus = 'PPSTATUS_SUBMT'          
          
declare @authorizedProtocols table (ResourceId int, AccessLevel int)     
insert into @authorizedProtocols           
 select * from fnadmqgetauthorizedresourcelist (@domainuserid, @protocolResourceType)          
With PendingItems AS          
    ( SELECT            
   spon.[name] as 'SponsorName',            
   fct.ProtocolId ,            
   fct.FormsID,            
   prt.Title,            
   prt.ProtocolNumber,            
   pip.lastname + ', ' +  pip.firstname as 'PiName',            
   fct.SubmissionDate,            
   fct.BoardName,            
   fct.ReviewType,            
   fct.MeetingDate,            
   fct.BoardStatus,            
   posty.[Name] as 'OverallStatus'    
                      
  from @authorizedProtocols ara           
  inner join PendingApplications_Fct fct          
  on ara.Resourceid = fct.Fwkresourceid           
  inner join Protocol prt          
  on prt.[Id] = fct.ProtocolId          
  inner join ProtocolOverallStatusType posty          
  on posty.[id] = prt.[OverallStatusId]          
  left join AdmPerson pip          
  on prt.pipersonid = pip.[id]          
  left join AdmSponsor spon          
  on prt.Admsponsorid = spon.[id]          
  where ara.AccessLevel !=  @keyGiverAccessLevel          
  and prt.moduletype = @module    
  and IsNull(prt.Title,'*') like @protocolTitle                      
  and IsNull(prt.version,'*') like @versionNo                      
  and IsNull(prt.protocolnumber,'*') like @protocolNo                      
  and(DateDiff(dd,cast(IsNull(@expDateFrom, '1/1/1900') as Datetime),cast(IsNull(prt.ExpirationDate,'1/1/1900')as DateTime))>= 0     
  and DateDiff(dd,cast(IsNull(@expDateTo,'12/31/2099') as Datetime),cast(IsNull(prt.ExpirationDate,'1/1/1900') as Datetime))<=0)    
  and IsNull(spon.Name,'*') like @sponsorName                      
  and IsNull(cast(prt.PiPersonId as varchar(20)),'*') like isNull(cast(@piId as varchar(20)),'%')                       
union                
  select          
         
   spon.[name] as 'SponsorName',            
   pp.ProtocolId ,            
   pp.[Name] as 'FormsID',            
   prt.Title,            
   prt.ProtocolNumber,            
   pip.lastname + ', ' +  pip.firstname as 'PiName',            
   pp.ReceivedDate as 'SubmissionDate', -- todo: this will be a field on the protocolProcess at some point            
   null as 'BoardName',            
   null as 'ReviewType',            
   null as 'MeetingDate',            
   null as 'BoardStatus',            
   'Pending' as 'OverallStatus'            
                     
  from @authorizedProtocols ara           
  inner join Protocol prt          
  on ara.Resourceid = prt.Fwkresourceid           
  inner join ProtocolProcess pp          
  on pp.ProtocolId = prt.[Id]          
  left join AdmSponsor spon          
  on prt.Admsponsorid = spon.[id]          
  left join AdmPerson pip          
  on prt.pipersonid = pip.[id]          
            
  where          
  ara.AccessLevel !=  @keyGiverAccessLevel          
  and (pp.Status = @pendingProcessStatus          
  or pp.Status = @submittedProcessStatus)          
  and prt.MarkForDeletion = 0      
  and prt.moduletype = @module          
  -- Pending Processes that have already made it to Rex and back will be in the ProtocolSubmission          
  -- table as well, and we don't want both records to show up          
  and not exists (Select ProtocolProcessId from ProtocolSubmission where ProtocolProcessId = pp.[Id])          
  and IsNull(prt.Title,'*') like @protocolTitle                      
  and IsNull(prt.version,'*') like @versionNo                      
  and IsNull(prt.protocolnumber,'*') like @protocolNo                      
  and(DateDiff(dd,cast(IsNull(@expDateFrom, '1/1/1900') as Datetime),cast(IsNull(prt.ExpirationDate,'1/1/1900')as DateTime))>= 0     
  and DateDiff(dd,cast(IsNull(@expDateTo,'12/31/2099') as Datetime),cast(IsNull(prt.ExpirationDate,'1/1/1900') as Datetime))<=0)    
  and IsNull(spon.Name,'*') like @sponsorName                      
  and IsNull(cast(prt.PiPersonId as varchar(20)),'*') like isNull(cast(@piId as varchar(20)),'%')                       
  )    
 Select ProtocolId from PendingItems     
 Order by     
  Case @sortOrder                     
     When 0 then                        
      CASE @SortColumn                       
    WHEN 'Title' THEN [Title]                                
    When 'PIName' Then [piName]                      
    When 'SponsorName' Then [SponsorName]    
    When 'OverallStatus' Then OverallStatus                             
    When 'ProtocolNumber' THEN [ProtocolNumber]    
    When 'FormsId'   Then [FormsId]                   
    When 'BoardStatus'   Then [BoardStatus]    
    When 'ReviewType' Then [ReviewType]    
    When 'MeetingDate' Then [MeetingDate]    
    When 'BoardName' Then [BoardName]        
    END              
       END Desc,               
    CASE @SortOrder                      
      When 0 then                
      CASE @SortColumn                       
    When 'SubmissionDate' Then [SubmissionDate]                       
    ELSE [SubmissionDate]                
    END                           
    END Desc,                      
    CASE @SortOrder                      
    When 1 then                       
      CASE @SortColumn                       
    WHEN 'Title' THEN [Title]                                
    When 'PIName' Then [piName]                      
    When 'SponsorName' Then [SponsorName]    
    When 'OverallStatus' Then OverallStatus                                                                                     
    When 'ProtocolNumber' THEN [ProtocolNumber]    
    When 'FormsId'   Then [FormsId]                   
    When 'BoardStatus'   Then [BoardStatus]    
    When 'ReviewType' Then [ReviewType]    
    When 'MeetingDate' Then [MeetingDate]    
    When 'BoardName' Then [BoardName]                        
    END                
    END ASC,              
    CASE @SortOrder                
     When 1 then                
      case @SortColumn                        
    When 'SubmissionDate' Then [SubmissionDate]                       
    ELSE [SubmissionDate]                
       END                          
    END          
          
          
select max(enddate) as 'lastfeedrundate'          
from SvcFeedRun          
where svcfeedtypeid in (select [Id] from SvcFeedType where [Name] = 'NewProtocol_RexToAsset')          
and svcfeedstatustypeid in (select [Id] from SvcFeedStatusType where [Name] = 'Completed')          
          
end          
          
          
    
                  

GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Creating [dbo].[GetWorkflowHistoryTest]'
GO
/************************************************************************************************    
* Name:  [GetWorkflowHistory]                                                              
* Purpose: This stored procedure gets the history of completed activities, associated with execution id   
*  id    
*      
* PARAMETERS      
* Name   Description    
* ------------------------- -----------------------------    
* @ExecutionId    Workflow execution Id    
*    
************************************************************************************************    
*Call: [GetWorkflowHistory] 6    
************************************************************************************************/    
CREATE procedure [dbo].[GetWorkflowHistoryTest]   
(    
 @ExecutionId int     
)    
as    
begin    
set nocount on    
  
DECLARE @hourDiff int   
set @hourDiff = (select datediff(hour, getdate(), getutcdate())) * -1      
DECLARE @Email TABLE (                  
   [ExecutionDetailsId] INT,                
   [EmailDescription] nvarchar(max)                
   )                  
   Insert Into @Email([ExecutionDetailsId],[EmailDescription]) EXEC [dbo].[GetWFEMailDecription] @ExecutionId   
              
Select  swd.[ActionName],      
  DATEADD(hh,@hourDiff,swd.[StartedOn]) as StartedOn,      
  swd.[outPut],      
  swd.[ActionType],      
  swl.[Description] as [ActivityDescription],      
  rtrim(ltrim(adp.LastName)) +', '+rtrim(ltrim(adp.FirstName)) as FullName, 
  fwku.UserName,      
  DATEADD(hh,@hourDiff,swd.[LastUpdatedDateTime])as[ExecutionEndDate],  
  swl.[Comments] as [Comments],  
  email.EmailDescription  
    
from swexecutionDetails  swd      
left join swactivitylist swl       
On swd.ActionName = swl.ActivityName      
and swl.ExecutionId = swd.ExecutionId      
left join swvirtualUser swvu      
On swvu.Id = swl.VirtualuserId      
Left join fwkDomainUser fwku      
On fwku.Id= swvu.UserId --adp.FwkDomainUserId  
Left join admperson adp      
On adp.FwkDomainUserId = Fwku.Id   
left join @Email email  
On email.ExecutionDetailsId = swd.[Id]  
where swd.executionid= @ExecutionId      
order by swd.[StartedOn]   
End  
  
  
  
  
  
GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Creating [dbo].[InjectExpiredRexAgreements]'
GO


/***************************************************************************
* Name:			InjectExpiredRexAgreements
* Purpose:		Using table Stg_REX_ExpiredAgreements, inject expired REX
*				agreement data.
*
* SCRAPED DATA		Coded
* -------------		-----
* Cost Center		
* Sponsor
* Fund
*
*
* AGREEMENT Tables Maintained
* Name									Coded	Operations					Done	
* -------------							-----	-------------------------	----
* AgrAgreement							I/U		Insert/Update				Y
* AgrBudgetContainer					I		Insert/Update				Y
* AgrBudgetContainerView				I		Insert/Update				Y
* AgrBudget								I		Insert/Update				Y
* SvcEntity_FwkDomainOrganization_Map			Insert/Update				Y
* AgrActivity									Insert/Update				Y
* SvcEntity								I		Insert						Y
* FwkResource							I		Insert						Y
* AnnAnnotationContainer				I		Insert						Y
* SvcEntity_AdmFacility_map						Insert/Update (Primary)		Y
* SvcEntity_AdmAdministrator_map				N/A
* SvcEntity_AdmStaffedPerson_map				Insert/Update (PI)			Y
*
* FUND Tables Maintained
* Name									Coded	Operations					Done	
* -------------							-----	-------------------------	----
* AgrFund										Insert/Update				Y
* SvcEntity										Insert						Y
* AgrFund_AgrAgreement_Map						Insert/Update				Y
* AgrCostCenter_AgrFund_Map						Insert/Update				Y
* AgrCostCenter									Insert						Y
* SvcEntity_AdmSponsor_map						Insert/Update				Y
* AdmSponsor									Insert/Update				Y
* 
* 
* 
* PARAMETERS
* Name				Description					
* -------------		-----------------------------------------------------------
* n/a
*
* ERRORS USED		Description
* -------------		-----------------------------------------------------
* n/a
*
* RETURN VALUE
* Value    			Description					
* --------------	------------------------------------------------------
* @_exitStatus		An exit status of either true or false
***************************************************************************/
Create PROCEDURE [dbo].[InjectExpiredRexAgreements]
AS
BEGIN

	SET NOCOUNT ON

	Begin Try

	begin transaction InjectExpiredRexAgreements



/*
  **************************************
  * N E W  A G R E E M E N T S         *
  **************************************
*/
	-- NEW FwkResources
	SET IDENTITY_INSERT FwkResource ON

	INSERT	FwkResource (Id, FwkResourceTypeId)
	SELECT	DISTINCT s.FwkResourceId, 1
	FROM	Stg_IE_DemogFeed_ExpiredAgreements s
	WHERE	s.IsInInfoED = 0 and s.FwkResourceId is not null and s.IsNewAgreement=1 and s.IsCurrentFund = 1

	SET IDENTITY_INSERT FwkResource OFF

	-- NEW SvcEntity
	SET IDENTITY_INSERT SvcEntity ON

	INSERT	SvcEntity (Id, SvcEntityTypeId, FwkResourceId)
	SELECT	DISTINCT s.SvcEntityId, 1, s.FwkResourceId
	FROM	Stg_IE_DemogFeed_ExpiredAgreements s
	WHERE	s.IsInInfoED = 0 and s.SvcEntityId is not null and s.IsNewAgreement=1 and s.IsCurrentFund = 1

	SET IDENTITY_INSERT SvcEntity OFF

	-- NEW AgrBudgetContainer
	SET IDENTITY_INSERT AgrBudgetContainer ON

	INSERT			AgrBudgetContainer (Id, Name, Description, IndirectCostBaseId, AgrBudgetTemplateTypeId)
	SELECT DISTINCT s.AgrBudgetContainerId, 
					CAST(s.AgrAgreementID AS varchar) + ' ' + s.Folder_Number, 
					'Agreement Budget for Rex agreement Id ' + CAST(s.AgrAgreementID AS varchar), 
					coalesce((select p.finICBaseTypeId from FinPSICBaseType p 
								 where p.[id] = isNull(s.ic_base_int,0))
							 ,1/* Default to MTDC if nothing else */),
					1	-- hard-coded value for budget template type Id
	FROM			Stg_IE_DemogFeed_ExpiredAgreements s
	WHERE	s.IsInInfoED = 0 and s.AgrBudgetContainerId is not null and s.IsNewAgreement=1 and s.IsCurrentFund = 1

	SET IDENTITY_INSERT AgrBudgetContainer OFF

	--NEW AgrBudgetContainerView for awarded
	SET IDENTITY_INSERT AgrBudgetContainerView ON

	INSERT INTO AgrBudgetContainerView (Id,AgrBudgetContainerId, AgrBudgetViewTypeId, TargetPatientNumber
									, PerCapitaValue, InflationRate, CurrentGrantYear)
	SELECT s.AgrBudgetContainerViewId,s.AgrBudgetContainerId
					,3/*Awarded Budget View Type*/,0,0,0,1 
	FROM Stg_IE_DemogFeed_ExpiredAgreements s
	WHERE	s.IsInInfoED = 0 and s.AgrBudgetContainerViewId is not null 
			and (s.IsNewAgreement=1 or not exists(Select 1 from agragreement a
													inner join agrbudgetcontainer bc on bc.id = a.agrbudgetcontainerId
													inner join agrbudgetcontainerview bcv on bcv.agrbudgetcontainerId = bc.id
																and bcv.AgrBudgetViewTypeId = 3
													where a.foldernumber = left(s.folder_number,11)))
			and s.IsCurrentFund = 1

	INSERT INTO AgrBudgetContainerView (Id,AgrBudgetContainerId, AgrBudgetViewTypeId, TargetPatientNumber
									, PerCapitaValue, InflationRate, CurrentGrantYear)
	SELECT s.AgrBudgetContainerViewId1,s.AgrBudgetContainerId
					,1/*Pending Budget View Type*/,0,0,0,1 
	FROM Stg_IE_DemogFeed_ExpiredAgreements s
	WHERE	s.IsInInfoED = 0 and s.AgrBudgetContainerViewId1 is not null
			and (s.IsNewAgreement=1 or not exists(Select 1 from agragreement a
													inner join agrbudgetcontainer bc on bc.id = a.agrbudgetcontainerId
													inner join agrbudgetcontainerview bcv on bcv.agrbudgetcontainerId = bc.id
																and bcv.AgrBudgetViewTypeId = 1
													where a.foldernumber = left(s.folder_number,11)))
			and s.IsCurrentFund = 1

	SET IDENTITY_INSERT AgrBudgetContainerView OFF

	-- NEW AnnAnnotationContainer
	SET IDENTITY_INSERT AnnAnnotationContainer ON

	INSERT	AnnAnnotationContainer (Id, SbsEntityTypeId)
	SELECT	distinct s.AnnAnnotationContainerId, 21
	FROM	Stg_IE_DemogFeed_ExpiredAgreements s
	WHERE	s.IsInInfoED = 0 and s.AnnAnnotationContainerId is not null and s.IsNewAgreement=1 and s.IsCurrentFund = 1

	SET IDENTITY_INSERT AnnAnnotationContainer OFF

/*
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	I N S E R T  A G R A G R E E M E N T
	Insert the agreement that is flagged as a new agreement based on its current fund.
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*/
	SET IDENTITY_INSERT AgrAgreement ON

	INSERT	AgrAgreement
			(
				Id,
				CurrentId,
				PIPersonId,
				AgrTransactionTypeId,
				AgrAgreementTypeId,
				AgrAgreementStatusTypeId,
				OverallStatus,
				FolderNumber,
				ParentFolderNumber,
				ShortTitle,
				Title,
				DocumentNumber,
				RexOwned,
				IsCurrent,
				IsAmendment,
				AgrBudgetContainerId,
				LegacyIdentifier,
				LegacySystemName,
				ReceivedDate,
				ProjectStartDate,
				ProjectEndDate,
				AgrNumberSchemeTypeId,
				Resubmission,
				Response,
				RFAID,
				RFATitle,
				InsertedDate,
				SvcEntityId,
				FwkResourceId,
				AnnAnnotationContainerId,
				DateLastModified
			)
	SELECT 	s.AgrAgreementId,
				s.AgrAgreementId,
				ra.PIPersonId, -- From REX
				ra.AgrTransactionTypeId,-- From REX
				ra.AgrAgreementTypeId,-- From REX
				ra.AgrAgreementStatusTypeId,-- From REX
				ra.OverallStatus,-- From REX
				ra.FolderNumber,-- From REX
				ra.ParentFolderNumber,-- From REX
				ra.ShortTitle,-- From REX
				ra.Title,-- From REX
				ra.DocumentNumber,-- From REX
				ra.RexOwned,-- From REX
				ra.IsCurrent,-- From REX
				ra.IsAmendment,-- From REX
				s.AgrBudgetContainerId,
				ra.LegacyIdentifier,-- From REX
				ra.LegacySystemName,-- From REX
				ra.ReceivedDate, -- From REX
				ra.ProjectStartDate,-- From REX
				ra.ProjectEndDate,-- From REX
				ra.AgrNumberSchemeTypeId,-- From REX
				ra.Resubmission,-- From REX
				ra.Response,-- From REX
				ra.RFAID,-- From REX
				ra.RFATitle,-- From REX
				ra.InsertedDate,
				s.SvcEntityId,
				s.FwkResourceId,
				s.AnnAnnotationContainerId,
				ra.DateLastModified
	FROM	Stg_IE_DemogFeed_ExpiredAgreements s
	INNER JOIN Stg_Rex_ExpiredAgreements ra on ra.foldernumber = left(s.folder_number,11)
	WHERE	s.IsInInfoED = 0 and s.AgrAgreementID is not null and s.SvcEntityId is not null and s.FwkResourceId is not null 
			 and s.IsNewAgreement=1 and s.IsCurrentFund = 1

	SET IDENTITY_INSERT AgrAgreement OFF

/*
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	I N S E R T  S V C E N T I T Y  F A C I L I T Y  M A P
	Insert the facility map for an agreement with no prior facility map row.
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*/
	INSERT	SvcEntity_AdmFacility_Map ( SvcEntityId, AdmFacilityId, AdmFacilityRelationshipTypeId, PercentActivity, DateCreated)
	SELECT	s.SvcEntityId, fm.AdmFacilityId, fm.AdmFacilityRelationshipTypeId, fm.PercentActivity, fm.DateCreated
	FROM	Stg_IE_DemogFeed_ExpiredAgreements s
	INNER JOIN Stg_Rex_ExpiredAgreements ra on ra.foldernumber = left(s.folder_number,11)
	INNER JOIN Stg_Rex_ExpiredAgreement_FacilityMap fm on fm.svcentityid = ra.svcentityid
	WHERE	s.IsInInfoED = 0 and s.SvcEntityId is not null and fm.AdmFacilityId is not null
			 and s.IsNewAgreement=1 and s.IsCurrentFund = 1
/*
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	I N S E R T  S V C E N T I T Y  O R G A N I Z A T I O N  M A P
	Insert the organization map for an agreement that has no organization map.
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*/
	Insert Into svcentity_fwkDomainOrganization_map(
		 SvcEntityId
		,fwkDomainOrganizationId
		,fwkOrganizationRelationshipTypeId
		,DateCreated
	)
	Select s.svcEntityId, fm.fwkDomainOrganizationId, fm.fwkOrganizationRelationshipTypeId , fm.DateCreated
	FROM	Stg_IE_DemogFeed_ExpiredAgreements s
	INNER JOIN Stg_Rex_ExpiredAgreements ra on ra.foldernumber = left(s.folder_number,11)
	INNER JOIN Stg_Rex_ExpiredAgreement_OrganizationMap fm on fm.svcentityid = ra.svcentityid
	WHERE	s.IsInInfoED = 0  and s.SvcEntityId is not null and fm.fwkDomainOrganizationId is not null
		 and s.IsNewAgreement=1 and s.IsCurrentFund = 1
/*
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	I N S E R T  A C T I V I T Y
	Insert the AgrActivity table for a new agreement.
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*/
	Insert Into AgrActivity(
		 AgrAgreementId
		,AgrActivityTypeid
		,ActivityType
		,ActivitySubType
		,ActivitySubSubType
		,SequenceNo
	)
	Select s.AgrAgreementId, fm.AgrActivityTypeid,fm.ActivityType,fm.ActivitySubType,fm.ActivitySubSubType,fm.SequenceNo
	FROM	Stg_IE_DemogFeed_ExpiredAgreements s
	INNER JOIN Stg_Rex_ExpiredAgreements ra on ra.foldernumber = left(s.folder_number,11)
	INNER JOIN Stg_Rex_ExpiredAgreement_Activity fm on fm.AgrAgreementid = ra.id
	WHERE	s.IsInInfoED = 0 and s.AgrAgreementID is not null  and s.IsNewAgreement=1 and s.IsCurrentFund = 1
/*
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	I N S E R T  M I L E S T O N E
	Insert the AgrMilestone table for a new agreement.
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*/
	Insert Into AgrMilestone( 
			AgrAgreementId, MilestoneTypeId, AmountDue, DueDate, AmountReceived, CompletedDate
	  , InsertedBy, ModifiedBy, ModifiedDate, [Description], DateCreated
	)
	Select	s.AgrAgreementId, fm.MilestoneTypeId, fm.AmountDue, fm.DueDate, fm.AmountReceived, fm.CompletedDate
	  , fm.InsertedBy, fm.ModifiedBy, fm.ModifiedDate, fm.[Description], fm.DateCreated	
	FROM	Stg_IE_DemogFeed_ExpiredAgreements s
	INNER JOIN Stg_Rex_ExpiredAgreements ra on ra.foldernumber = left(s.folder_number,11)
	INNER JOIN Stg_Rex_ExpiredAgreement_Milestone fm on fm.AgrAgreementid = ra.id
	WHERE	s.IsInInfoED = 0 and s.AgrAgreementID is not null  and s.IsNewAgreement=1 and s.IsCurrentFund = 1
/*
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	I N S E R T  T E R M S  A N D  C O N D I T I O N S
	Insert the AgrTermsAndConditions table for a new agreement.
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*/
	Insert Into AgrTermsAndConditions(
      [AgrAgreementId],[Terms],[ConflictOfInterest],[StudyHuman],[StudyAnimal],[InsertedBy]
			,[InsertedDate] ,[ModifiedBy],[ModifiedDate])
	Select s.[AgrAgreementId],fm.[Terms],fm.[ConflictOfInterest],fm.[StudyHuman],fm.[StudyAnimal],fm.[InsertedBy]
			,fm.[InsertedDate] ,fm.[ModifiedBy],fm.[ModifiedDate]
	FROM	Stg_IE_DemogFeed_ExpiredAgreements s
	INNER JOIN Stg_Rex_ExpiredAgreements ra on ra.foldernumber = left(s.folder_number,11)
	INNER JOIN Stg_Rex_ExpiredAgreement_TermsAndConditions fm on fm.AgrAgreementid = ra.id
	WHERE	s.IsInInfoED = 0 and s.AgrAgreementID is not null  and s.IsNewAgreement=1 and s.IsCurrentFund = 1

/*
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	I N S E R T  S V C E N T I T Y  S T A F F E D  P I  P E R S O N  
	Insert the PI into the SvcEntity_StaffedPerson_Map table for a new agreement.
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*/
	Insert Into SvcEntity_AdmStaffedPerson_Map(
		 SvcEntityId
		,AdmPersonId
		,AdmStaffedPersonTypeId
		,DateCreated
	)
	Select s.svcEntityId, fm.AdmPersonId, fm.AdmStaffedPersonTypeId , fm.DateCreated
	FROM	Stg_IE_DemogFeed_ExpiredAgreements s
	INNER JOIN Stg_Rex_ExpiredAgreements ra on ra.foldernumber = left(s.folder_number,11)
	INNER JOIN Stg_Rex_ExpiredAgreement_StaffedPersonMap fm on fm.svcentityid = ra.svcentityid
	WHERE	s.IsInInfoED = 0  and s.SvcEntityId is not null and fm.AdmPersonId is not null
			 and s.IsNewAgreement=1 and s.IsCurrentFund = 1
/*
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	I N S E R T  S V C E N T I T Y  A D M S P O N S O R 
	Insert the Sponsor into the SvcEntity_AdmSponsor_Map table for a new agreement.
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*/
	Insert Into SvcEntity_AdmSponsor_Map(
		 SvcEntityId
		,AdmSponsorId
		,AdmSponsorRelationTypeId
		,SponsorNumber
		,DateCreated
		,CFDANumber
	)
	Select s.svcEntityId, fm.AdmSponsorId, fm.AdmSponsorRelationTypeId,
		fm.SponsorNumber, fm.DateCreated ,fm.CFDANumber
	FROM	Stg_IE_DemogFeed_ExpiredAgreements s
	INNER JOIN Stg_Rex_ExpiredAgreements ra on ra.foldernumber = left(s.folder_number,11)
	INNER JOIN Stg_Rex_ExpiredAgreement_SponsorMap fm on fm.svcentityid = ra.svcentityid
	WHERE	s.IsInInfoED = 0  and s.SvcEntityId is not null and fm.AdmSponsorId is not null
		 and s.IsNewAgreement=1 and s.IsCurrentFund = 1
/*
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	I N S E R T  S V C E N T I T Y  F O R  N E W  F U N D S 
	Insert the service entity for new funds.
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*/
	SET IDENTITY_INSERT SvcEntity ON

	INSERT	SvcEntity (Id, SvcEntityTypeId, FwkResourceId)
	SELECT	s.AgrFundSvcEntityId, 3, s.FwkResourceId
	FROM	Stg_IE_DemogFeed_ExpiredAgreements s
	WHERE	s.IsNewFund = 1 and s.IsValid = 1 

	SET IDENTITY_INSERT SvcEntity OFF
/*
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	I N S E R T  A G R F U N D  
	Insert the fund into the AgrFund table for a new fund.
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*/
	SET IDENTITY_INSERT AgrFund ON

	INSERT		AgrFund (
					Id, SvcEntityId, FinAccountCycleTypeId, FundNumber, AgrFundStatusTypeId, 
					AgrFundAwardTypeId, AgrFundOverheadClassificationId, CFDA, 
					DocumentLetter, FundShortTitle, FundTitle, BusinessUnitId, RexOwned, 
					ActivationDate, EffectiveDate, AgrFundTypeId, AgrFundSubTypeId, ManagerId
					)
	SELECT			s.AgrFundId, s.SvcEntityId, s.FinAccountCycleTypeId, s.project_grant, s.AgrFundStatusTypeId, 
					s.AgrFundAwardTypeId, s.AgrFundOverheadClassificationId, s.cfda_number, 
					s.doc_letter, left(s.Description,50), left(s.long_Description,128), s.BusinessUnitId, 
					case IsNull(ltrim(rtrim(s.folder_number)),'') when '' then 0 else 1 end as RexOwned, 
					s.ActivationDate, s.Effective_Date, 1, s.AgrFundSubTypeId, s.PI_AdmPersonId
	FROM		Stg_IE_DemogFeed_ExpiredAgreements s
	WHERE		s.IsNewFund = 1 and s.IsValid = 1 

	SET IDENTITY_INSERT AgrFund OFF

/*
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	I N S E R T  A G R F U N D _ A G R A G R E E M E N T _ M A P  
	Insert the fund into the AgrFund_AgrAgreement_Map table for a new agreement.
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*/
	SET IDENTITY_INSERT AgrFund_AgrAgreement_Map ON

	INSERT	AgrFund_AgrAgreement_Map (
				Id, AgrFundId, AgrAgreementId, SvcEntityId, FinAccountCycleTypeId, FundNumber, 
				AgrFundStatusTypeId, AgrFundAwardTypeId, AgrFundOverheadClassificationId, 
				CFDA, DocumentLetter, FundShortTitle, FundTitle, EffectiveDate, 
				BusinessUnitId, RexOwned, ActivationDate, AgrFundTypeId, AgrFundSubTypeId, ManagerId
				)
	SELECT		fm.Id, fm.AgrFundId, fm.AgrAgreementId, fm.SvcEntityId,
				fm.FinAccountCycleTypeId, fm.FundNumber, fm.AgrFundStatusTypeId, fm.AgrFundAwardTypeId, 
				fm.AgrFundOverheadClassificationId, fm.cfda, fm.DocumentLetter, fm.FundShortTitle,
				fm.FundTitle, fm.EffectiveDate, fm.BusinessUnitId, fm.RexOwned, fm.ActivationDate, 
				fm.AgrFundTypeId, fm.AgrFundSubTypeId, fm.ManagerId
	FROM	Stg_Rex_ExpiredAgreement_FundMap fm
	WHERE	fm.AgrAgreementId is not null and fm.SvcEntityId is not null

	SET IDENTITY_INSERT AgrFund_AgrAgreement_Map OFF
/*
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	I N S E R T  A G R B U D G E T  
	Insert the budget if this is a maintained agreement and there was no container view
	or this is a new agreement.
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*/
	SET IDENTITY_INSERT AgrBudget ON

	INSERT INTO AgrBudget (Id,AgrBudgetContainerViewId, AgrBudgetTypeId, StartDate, EndDate
							,[Year], IsAwarded, AgrFundAgreeMapId, IsAdjustment)
	SELECT DISTINCT fm.Id,case when s.IsNewAgreement = 1 or bcv.id is null then s.AgrBudgetContainerViewId else bcv.id end,fm.AgrBudgetTypeId
					,fm.StartDate
					,fm.EndDate
					,fm.[Year],fm.IsAwarded,fm.AgrFundAgreeMapId,fm.IsAdjustment 
	FROM Stg_IE_DemogFeed_ExpiredAgreements s
	INNER JOIN Stg_Rex_ExpiredAgreement_BudgetHeader fm on left(s.folder_number,11) = fm.foldernumber
	left outer join AgrAgreement a on a.foldernumber = fm.foldernumber
	left outer join AgrBudgetContainer bc on bc.Id = a.AgrBudgetContainerid
	left outer join AgrBudgetContainerView bcv on bcv.AgrBudgetContainerId = bc.id and bcv.agrbudgetviewtypeid = 3
	left outer join AgrBudget b on b.AgrBudgetContainerViewId = s.AgrBudgetContainerViewId
					and fm.startdate = b.startdate and fm.enddate = b.enddate 
					and fm.[year] = b.[year] and fm.IsAdjustment = b.IsAdjustment
					and fm.IsAwarded = b.IsAwarded
	WHERE	s.IsInInfoED = 0  and fm.agrbudgetviewtypeid = 3 
			and s.AgrBudgetContainerViewId is not null and b.Id is null
			and s.IsAgreementMaintained = 1 


	INSERT INTO AgrBudget (Id,AgrBudgetContainerViewId, AgrBudgetTypeId, StartDate, EndDate
							,[Year], IsAwarded, AgrFundAgreeMapId, IsAdjustment)
	SELECT DISTINCT fm.Id,case when s.IsNewAgreement = 1 or bcv.id is null then s.AgrBudgetContainerViewId1 else bcv.id end,fm.AgrBudgetTypeId
					,fm.StartDate
					,fm.EndDate
					,fm.[Year],fm.IsAwarded,fm.AgrFundAgreeMapId,fm.IsAdjustment 
	FROM Stg_IE_DemogFeed_ExpiredAgreements s
	INNER JOIN Stg_Rex_ExpiredAgreement_BudgetHeader fm on left(s.folder_number,11) = fm.foldernumber
	left outer join AgrAgreement a on a.foldernumber = fm.foldernumber
	left outer join AgrBudgetContainer bc on bc.Id = a.AgrBudgetContainerid
	left outer join AgrBudgetContainerView bcv on bcv.AgrBudgetContainerId = bc.id and bcv.agrbudgetviewtypeid = 1
	left outer join AgrBudget b on b.AgrBudgetContainerViewId = s.AgrBudgetContainerViewId1
					and fm.startdate = b.startdate and fm.enddate = b.enddate 
					and fm.[year] = b.[year] and fm.IsAdjustment = b.IsAdjustment
					and fm.IsAwarded = b.IsAwarded
	WHERE	s.IsInInfoED = 0  and fm.agrbudgetviewtypeid = 1 
			and s.AgrBudgetContainerViewId1 is not null  and b.Id is null
			and s.IsAgreementMaintained = 1

	SET IDENTITY_INSERT AgrBudget OFF


/*
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	I N S E R T  A G R B U D G E T  I T E M
	--NEW AgrBudgetItem for awarded for only new agreements that are maintained by this feed.
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*/
	INSERT INTO AgrBudgetItem (AgrBudgetId, AgrContainerAccountTemplateMapId, ItemValue)
	SELECT fm.AgrBudgetId,fm.AgrContainerAccountTemplateMapId,fm.ItemValue
	FROM Stg_Rex_ExpiredAgreement_BudgetItem fm 
	inner join agrbudget b on b.id = fm.agrbudgetid
/*
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	I N S E R T  A G R B U D G E T  I C  R A T E
	Insert the budget if this is a maintained agreement and there was no container view
	or this is a new agreement.
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*/
	INSERT INTO AgrBudgetICRate (AgrBudgetId,Rate,NumberOfMonths,SequenceNo,EffectiveDate)
	SELECT AgrBudgetId,Rate,NumberOfMonths,SequenceNo,EffectiveDate
	FROM Stg_Rex_ExpiredAgreement_BudgetICRate fm
	inner join agrbudget b on b.id = fm.agrbudgetid
/*
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	I N S E R T  A G R C O S T C E N T E R _ A G R F U N D _ M A P  
	Insert the fund into the AgrCostCenter_AgrFund_Map table for a new agreement.
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*/
	INSERT	AgrCostCenter_AgrFund_Map
				(AgrFundAgreementMapId, AgrCostCenterId, DateCreated, AgrCostCenterStatusTypeId)
	SELECT	fm.AgrFundAgreementMapId, fm.AgrCostCenterId, fm.DateCreated, fm.AgrCostCenterStatusTypeId
	FROM	Stg_Rex_ExpiredAgreement_CostCenterFundMap fm
	inner join agrFund_agragreement_map afm on afm.id = fm.AgrFundAgreementMapId

/*
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	I N S E R T  A G R A G R E E M E N T  H I E R A R C H Y  
	Insert the associated entries for AgrAgreementHierarchy table for the new agreements.
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*/
	INSERT	AgrAgreementHierarchy (ParentFolderNumber,FolderNumber,Sequence,IdentityTag)
	SELECT	distinct h.ParentFolderNumber,h.FolderNumber,h.Sequence,h.IdentityTag
	FROM	Stg_Rex_ExpiredAgreement_hierarchy h
	WHERE not exists(Select 1 from AgrAgreementHierarchy h1 
					where h1.ParentFolderNumber = h.ParentFolderNumber
						and h1.FolderNumber = h.FolderNumber)

	commit transaction InjectExpiredRexAgreements

	End Try

    BEGIN CATCH
    DECLARE 
        @ErrorMessage    NVARCHAR(4000),
        @ErrorNumber     INT,
        @ErrorSeverity   INT,
        @ErrorState      INT,
        @ErrorLine       INT,
        @ErrorProcedure  NVARCHAR(200);

    -- Assign variables to error-handling functions that 
    -- capture information for RAISERROR.
    SELECT 
        @ErrorNumber = ERROR_NUMBER(),
        @ErrorSeverity = ERROR_SEVERITY(),
        @ErrorState = ERROR_STATE(),
        @ErrorLine = ERROR_LINE(),
        @ErrorProcedure = ISNULL(ERROR_PROCEDURE(), '-');

    -- Building the message string that will contain original
    -- error information.
    SELECT @ErrorMessage = 
        N'Error %d, Level %d, State %d, Procedure %s, Line %d, ' + 
            'Message: '+ ERROR_MESSAGE();

	IF XACT_STATE() <> 0 Rollback transaction InjectExpiredRexAgreements

    -- Raise an error: msg_str parameter of RAISERROR will contain
    -- the original error information.
    RAISERROR 
        (
        @ErrorMessage, 
        @ErrorSeverity, 
        1,               
        @ErrorNumber,    -- parameter: original error number.
        @ErrorSeverity,  -- parameter: original error severity.
        @ErrorState,     -- parameter: original error state.
        @ErrorProcedure, -- parameter: original error procedure name.
        @ErrorLine       -- parameter: original error line number.
        );
		return 99
    END CATCH;
END



GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Creating [dbo].[MergeAdmSponsors]'
GO


Create procedure [dbo].[MergeAdmSponsors]
(
	@fromId int,
	@toId int
)
AS

BEGIN

  declare @myRowCount int -- Local @@ROWCOUNT


  if @fromId = @toId
  begin
    select 'Id values cannot be the same (' + convert(varchar,@fromId) + ')'
    return
  end

  select @myRowCount=count(*) from AdmSponsor
  where Id = @toId

  if 0 = @myRowCount
  begin
    select '"TO" Id is invalid (' + convert(varchar,@toId) + ')'
    return
  end 


  begin transaction


  BEGIN TRY

  Declare @MapTable  as table(mapId int)

  insert into PreMergeAdmSponsor
  ( Id, Name, ShortName, Description, AdmSponsorTypeId, DateCreated,
	RexSponsorId, InfoEdSponCode, PSCustCode )
  select Id, Name, ShortName, Description, AdmSponsorTypeId, getdate(),
	RexSponsorId, InfoEdSponCode, PSCustCode
  from AdmSponsor
  where Id = @fromId

  select @myRowCount = @@ROWCOUNT

  if 0 = @myRowCount
  begin
    rollback transaction
    select '"FROM" Id is invalid (' + convert(varchar,@fromId) + ')'
    return
  end 


  -- AdmSponsor_COIOrganization_Map table
  insert into AdmSponsorMergeHistory
  ( NewId, OldId, TableName, IdValue, Comments )
  select @toId, @fromId, 'AdmSponsor_COIOrganization_Map', COIOrganizationId, 'COIOrganizationId'
  from AdmSponsor_COIOrganization_Map
  where AdmSponsorId = @fromId

  select @myRowCount = @@ROWCOUNT

  if @myRowCount > 0
  begin

    insert into @MapTable (mapId)
    select COIOrganizationId
    from AdmSponsor_COIOrganization_Map
    where AdmSponsorId in (@fromId, @toId)

    delete AdmSponsor_COIOrganization_Map
    where AdmSponsorId in (@fromId, @toId)

    insert into AdmSponsor_COIOrganization_Map
    ( AdmSponsorId, COIOrganizationId )
    select distinct @toId, mapId from @MapTable
  end


  -- AgrSubContractor table
  insert into AdmSponsorMergeHistory
  ( NewId, OldId, TableName, IdValue )
  select @toId, @fromId, 'AgrSubContractor', Id
  from AgrSubContractor
  where AdmSponsorId = @fromId

  select @myRowCount = @@ROWCOUNT

  if @myRowCount > 0
  begin
    update AgrSubContractor
    set AdmSponsorId = @toId
    where AdmSponsorId = @fromId
  end


  -- ClinicalTrialBudget table
  insert into AdmSponsorMergeHistory
  ( NewId, OldId, TableName, IdValue )
  select @toId, @fromId, 'ClinicalTrialBudget', Id
  from ClinicalTrialBudget
  where SponsorId = @fromId

  select @myRowCount = @@ROWCOUNT

  if @myRowCount > 0
  begin
    update ClinicalTrialBudget
    set SponsorId = @toId
    where SponsorId = @fromId
  end


  -- Protocol table
  insert into AdmSponsorMergeHistory
  ( NewId, OldId, TableName, IdValue )
  select @toId, @fromId, 'Protocol', Id
  from Protocol
  where AdmSponsorId = @fromId

  select @myRowCount = @@ROWCOUNT

  if @myRowCount > 0
  begin
    update Protocol
    set AdmSponsorId = @toId
    where AdmSponsorId = @fromId
  end


  -- ProtocolAdmSponsor_Map table
  insert into AdmSponsorMergeHistory
  ( NewId, OldId, TableName, IdValue, Comments )
  select @toId, @fromId, 'ProtocolAdmSponsor_Map', ProtocolId, 'ProtocolId'
  from ProtocolAdmSponsor_Map
  where AdmSponsorId = @fromId

  select @myRowCount = @@ROWCOUNT

  if @myRowCount > 0
  begin
    insert into @MapTable (mapId)
    select ProtocolId
    from ProtocolAdmSponsor_Map
    where AdmSponsorId in (@fromId, @toId)

    delete ProtocolAdmSponsor_Map
    where AdmSponsorId in (@fromId, @toId)

    insert into ProtocolAdmSponsor_Map
    ( AdmSponsorId, ProtocolId )
    select distinct @toId, mapId from @MapTable
  end


  -- QuestionnaireAnswer table
  insert into AdmSponsorMergeHistory
  ( NewId, OldId, TableName, IdValue )
  select @toId, @fromId, 'QuestionnaireAnswer', qa.Id
  from QuestionnaireAnswer qa
    inner join QuestionnaireVersion qv on qa.QuestionnaireVersionId = qv.Id 
    inner join Questionnaire q on qv.QuestionnaireId = q.Id 
  where
    q.Name like 'Sponsor%' and
    qa.ExternalId = @fromId

  select @myRowCount = @@ROWCOUNT

  if @myRowCount > 0
  begin
    update QuestionnaireAnswer
    set ExternalId = @toId
    from QuestionnaireAnswer qa
      inner join QuestionnaireVersion qv on qa.QuestionnaireVersionId = qv.Id 
      inner join Questionnaire q on qv.QuestionnaireId = q.Id 
    where
      q.Name like 'Sponsor%' and
      qa.ExternalId = @fromId
  end


  -- SvcEntity_AdmSponsor_Map table
  insert into AdmSponsorMergeHistory
  ( NewId, OldId, TableName, IdValue )
  select @toId, @fromId, 'SvcEntity_AdmSponsor_Map', Id
  from SvcEntity_AdmSponsor_Map
  where AdmSponsorId = @fromId

  select @myRowCount = @@ROWCOUNT

  if @myRowCount > 0
  begin
    update SvcEntity_AdmSponsor_Map
    set AdmSponsorId = @toId
    where AdmSponsorId = @fromId
  end



  -- AgrAgreement_Fct and AgrBudget_Fct table
  update AgrAgreement_Fct
  set SponsorId = @toId
  where SponsorId = @fromId

  update AgrBudget_Fct
  set SponsorId = @toId
  where SponsorId = @fromId

  delete AdmSponsor where Id = @fromId

  commit transaction

  END TRY
  BEGIN CATCH

    DECLARE @ErrorMessage NVARCHAR(4000)
    DECLARE @ErrorSeverity INT
    DECLARE @ErrorState INT

    SELECT @ErrorMessage = ERROR_MESSAGE(),
           @ErrorSeverity = ERROR_SEVERITY(),
           @ErrorState = ERROR_STATE();

    rollback transaction

    -- Use RAISERROR inside the CATCH block to return 
    -- error information about the original error that 
    -- caused execution to jump to the CATCH block.
    RAISERROR (@ErrorMessage, -- Message text.
               @ErrorSeverity, -- Severity.
               @ErrorState -- State
               )
  END CATCH

END

GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Creating [dbo].[SaveCOIEMailTemplate]'
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO

/***************************************************************************
* Name:			SaveCOIEMailTemplate
* Purpose:		Insert/Update a COIEMailTemplate
*
* PARAMETERS
* Name				Description					
* -------------			-----------------------------------------------------------
* @id				Unique id ( 0 for new records to be inserted)
* @type				Type of the email template
* @bodytext			body of the email
****************************************************************************/
CREATE PROCEDURE [dbo].[SaveCOIEMailTemplate] (

@id INT,
@type VARCHAR(50),
@bodyText VARCHAR(2048)

)

AS

BEGIN
	SELECT @id = id FROM COIEMailTemplate WHERE type = @type
	IF @id = 0
	BEGIN

		INSERT INTO COIEMailTemplate( 
						Type, 
						BodyText
					)
					VALUES
					( 
						@type,
						@bodyText
					)
		
		IF @@ERROR <> 0 GOTO ERROR_HANDLER
		
		SELECT @id = IDENT_CURRENT('COIEMailTemplate')

		SELECT @id

		
		RETURN 
	END
	ELSE
	BEGIN
		
		UPDATE COIEMailTemplate
		SET
			Type = @type,
			BodyText = @bodyText
		WHERE [Id] = @id
		
		IF @@ERROR <> 0 GOTO ERROR_HANDLER

		SELECT @id	
		RETURN
		
	END

	ERROR_HANDLER:
		IF @@ERROR <> 0 
		BEGIN
			RAISERROR('Unable to Save COI E-Mail Template', 16, 1)
			RETURN
		END
END

SET QUOTED_IDENTIFIER OFF 

GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Creating [dbo].[sp_alterdiagram]'
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

	CREATE PROCEDURE dbo.sp_alterdiagram
	(
		@diagramname 	sysname,
		@owner_id	int	= null,
		@version 	int,
		@definition 	varbinary(max)
	)
	WITH EXECUTE AS 'dbo'
	AS
	BEGIN
		set nocount on
	
		declare @theId 			int
		declare @retval 		int
		declare @IsDbo 			int
		
		declare @UIDFound 		int
		declare @DiagId			int
		declare @ShouldChangeUID	int
	
		if(@diagramname is null)
		begin
			RAISERROR ('Invalid ARG', 16, 1)
			return -1
		end
	
		execute as caller;
		select @theId = DATABASE_PRINCIPAL_ID();	 
		select @IsDbo = IS_MEMBER(N'db_owner'); 
		if(@owner_id is null)
			select @owner_id = @theId;
		revert;
	
		select @ShouldChangeUID = 0
		select @DiagId = diagram_id, @UIDFound = principal_id from dbo.sysdiagrams where principal_id = @owner_id and name = @diagramname 
		
		if(@DiagId IS NULL or (@IsDbo = 0 and @theId <> @UIDFound))
		begin
			RAISERROR ('Diagram does not exist or you do not have permission.', 16, 1);
			return -3
		end
	
		if(@IsDbo <> 0)
		begin
			if(@UIDFound is null or USER_NAME(@UIDFound) is null) -- invalid principal_id
			begin
				select @ShouldChangeUID = 1 ;
			end
		end

		-- update dds data			
		update dbo.sysdiagrams set definition = @definition where diagram_id = @DiagId ;

		-- change owner
		if(@ShouldChangeUID = 1)
			update dbo.sysdiagrams set principal_id = @theId where diagram_id = @DiagId ;

		-- update dds version
		if(@version is not null)
			update dbo.sysdiagrams set version = @version where diagram_id = @DiagId ;

		return 0
	END
	
GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Creating [dbo].[sp_creatediagram]'
GO

	CREATE PROCEDURE dbo.sp_creatediagram
	(
		@diagramname 	sysname,
		@owner_id		int	= null, 	
		@version 		int,
		@definition 	varbinary(max)
	)
	WITH EXECUTE AS 'dbo'
	AS
	BEGIN
		set nocount on
	
		declare @theId int
		declare @retval int
		declare @IsDbo	int
		declare @userName sysname
		if(@version is null or @diagramname is null)
		begin
			RAISERROR (N'E_INVALIDARG', 16, 1);
			return -1
		end
	
		execute as caller;
		select @theId = DATABASE_PRINCIPAL_ID(); 
		select @IsDbo = IS_MEMBER(N'db_owner');
		revert; 
		
		if @owner_id is null
		begin
			select @owner_id = @theId;
		end
		else
		begin
			if @theId <> @owner_id
			begin
				if @IsDbo = 0
				begin
					RAISERROR (N'E_INVALIDARG', 16, 1);
					return -1
				end
				select @theId = @owner_id
			end
		end
		-- next 2 line only for test, will be removed after define name unique
		if EXISTS(select diagram_id from dbo.sysdiagrams where principal_id = @theId and name = @diagramname)
		begin
			RAISERROR ('The name is already used.', 16, 1);
			return -2
		end
	
		insert into dbo.sysdiagrams(name, principal_id , version, definition)
				VALUES(@diagramname, @theId, @version, @definition) ;
		
		select @retval = @@IDENTITY 
		return @retval
	END
	
GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Creating [dbo].[sp_dropdiagram]'
GO

	CREATE PROCEDURE dbo.sp_dropdiagram
	(
		@diagramname 	sysname,
		@owner_id	int	= null
	)
	WITH EXECUTE AS 'dbo'
	AS
	BEGIN
		set nocount on
		declare @theId 			int
		declare @IsDbo 			int
		
		declare @UIDFound 		int
		declare @DiagId			int
	
		if(@diagramname is null)
		begin
			RAISERROR ('Invalid value', 16, 1);
			return -1
		end
	
		EXECUTE AS CALLER;
		select @theId = DATABASE_PRINCIPAL_ID();
		select @IsDbo = IS_MEMBER(N'db_owner'); 
		if(@owner_id is null)
			select @owner_id = @theId;
		REVERT; 
		
		select @DiagId = diagram_id, @UIDFound = principal_id from dbo.sysdiagrams where principal_id = @owner_id and name = @diagramname 
		if(@DiagId IS NULL or (@IsDbo = 0 and @UIDFound <> @theId))
		begin
			RAISERROR ('Diagram does not exist or you do not have permission.', 16, 1)
			return -3
		end
	
		delete from dbo.sysdiagrams where diagram_id = @DiagId;
	
		return 0;
	END
	
GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Creating [dbo].[sp_helpdiagramdefinition]'
GO

	CREATE PROCEDURE dbo.sp_helpdiagramdefinition
	(
		@diagramname 	sysname,
		@owner_id	int	= null 		
	)
	WITH EXECUTE AS N'dbo'
	AS
	BEGIN
		set nocount on

		declare @theId 		int
		declare @IsDbo 		int
		declare @DiagId		int
		declare @UIDFound	int
	
		if(@diagramname is null)
		begin
			RAISERROR (N'E_INVALIDARG', 16, 1);
			return -1
		end
	
		execute as caller;
		select @theId = DATABASE_PRINCIPAL_ID();
		select @IsDbo = IS_MEMBER(N'db_owner');
		if(@owner_id is null)
			select @owner_id = @theId;
		revert; 
	
		select @DiagId = diagram_id, @UIDFound = principal_id from dbo.sysdiagrams where principal_id = @owner_id and name = @diagramname;
		if(@DiagId IS NULL or (@IsDbo = 0 and @UIDFound <> @theId ))
		begin
			RAISERROR ('Diagram does not exist or you do not have permission.', 16, 1);
			return -3
		end

		select version, definition FROM dbo.sysdiagrams where diagram_id = @DiagId ; 
		return 0
	END
	
GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Creating [dbo].[sp_helpdiagrams]'
GO

	CREATE PROCEDURE dbo.sp_helpdiagrams
	(
		@diagramname sysname = NULL,
		@owner_id int = NULL
	)
	WITH EXECUTE AS N'dbo'
	AS
	BEGIN
		DECLARE @user sysname
		DECLARE @dboLogin bit
		EXECUTE AS CALLER;
			SET @user = USER_NAME();
			SET @dboLogin = CONVERT(bit,IS_MEMBER('db_owner'));
		REVERT;
		SELECT
			[Database] = DB_NAME(),
			[Name] = name,
			[ID] = diagram_id,
			[Owner] = USER_NAME(principal_id),
			[OwnerID] = principal_id
		FROM
			sysdiagrams
		WHERE
			(@dboLogin = 1 OR USER_NAME(principal_id) = @user) AND
			(@diagramname IS NULL OR name = @diagramname) AND
			(@owner_id IS NULL OR principal_id = @owner_id)
		ORDER BY
			4, 5, 1
	END
	
GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Creating [dbo].[sp_renamediagram]'
GO

	CREATE PROCEDURE dbo.sp_renamediagram
	(
		@diagramname 		sysname,
		@owner_id		int	= null,
		@new_diagramname	sysname
	
	)
	WITH EXECUTE AS 'dbo'
	AS
	BEGIN
		set nocount on
		declare @theId 			int
		declare @IsDbo 			int
		
		declare @UIDFound 		int
		declare @DiagId			int
		declare @DiagIdTarg		int
		declare @u_name			sysname
		if((@diagramname is null) or (@new_diagramname is null))
		begin
			RAISERROR ('Invalid value', 16, 1);
			return -1
		end
	
		EXECUTE AS CALLER;
		select @theId = DATABASE_PRINCIPAL_ID();
		select @IsDbo = IS_MEMBER(N'db_owner'); 
		if(@owner_id is null)
			select @owner_id = @theId;
		REVERT;
	
		select @u_name = USER_NAME(@owner_id)
	
		select @DiagId = diagram_id, @UIDFound = principal_id from dbo.sysdiagrams where principal_id = @owner_id and name = @diagramname 
		if(@DiagId IS NULL or (@IsDbo = 0 and @UIDFound <> @theId))
		begin
			RAISERROR ('Diagram does not exist or you do not have permission.', 16, 1)
			return -3
		end
	
		-- if((@u_name is not null) and (@new_diagramname = @diagramname))	-- nothing will change
		--	return 0;
	
		if(@u_name is null)
			select @DiagIdTarg = diagram_id from dbo.sysdiagrams where principal_id = @theId and name = @new_diagramname
		else
			select @DiagIdTarg = diagram_id from dbo.sysdiagrams where principal_id = @owner_id and name = @new_diagramname
	
		if((@DiagIdTarg is not null) and  @DiagId <> @DiagIdTarg)
		begin
			RAISERROR ('The name is already used.', 16, 1);
			return -2
		end		
	
		if(@u_name is null)
			update dbo.sysdiagrams set [name] = @new_diagramname, principal_id = @theId where diagram_id = @DiagId
		else
			update dbo.sysdiagrams set [name] = @new_diagramname where diagram_id = @DiagId
		return 0
	END
	
GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Creating [dbo].[sp_upgraddiagrams]'
GO

	CREATE PROCEDURE dbo.sp_upgraddiagrams
	AS
	BEGIN
		IF OBJECT_ID(N'dbo.sysdiagrams') IS NOT NULL
			return 0;
	
		CREATE TABLE dbo.sysdiagrams
		(
			name sysname NOT NULL,
			principal_id int NOT NULL,	-- we may change it to varbinary(85)
			diagram_id int PRIMARY KEY IDENTITY,
			version int,
	
			definition varbinary(max)
			CONSTRAINT UK_principal_name UNIQUE
			(
				principal_id,
				name
			)
		);


		/* Add this if we need to have some form of extended properties for diagrams */
		/*
		IF OBJECT_ID(N'dbo.sysdiagram_properties') IS NULL
		BEGIN
			CREATE TABLE dbo.sysdiagram_properties
			(
				diagram_id int,
				name sysname,
				value varbinary(max) NOT NULL
			)
		END
		*/

		IF OBJECT_ID(N'dbo.dtproperties') IS NOT NULL
		begin
			insert into dbo.sysdiagrams
			(
				[name],
				[principal_id],
				[version],
				[definition]
			)
			select	 
				convert(sysname, dgnm.[uvalue]),
				DATABASE_PRINCIPAL_ID(N'dbo'),			-- will change to the sid of sa
				0,							-- zero for old format, dgdef.[version],
				dgdef.[lvalue]
			from dbo.[dtproperties] dgnm
				inner join dbo.[dtproperties] dggd on dggd.[property] = 'DtgSchemaGUID' and dggd.[objectid] = dgnm.[objectid]	
				inner join dbo.[dtproperties] dgdef on dgdef.[property] = 'DtgSchemaDATA' and dgdef.[objectid] = dgnm.[objectid]
				
			where dgnm.[property] = 'DtgSchemaNAME' and dggd.[uvalue] like N'_EA3E6268-D998-11CE-9454-00AA00A3F36E_' 
			return 2;
		end
		return 1;
	END
	
GO
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
IF EXISTS (SELECT * FROM #tmpErrors) ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT>0 BEGIN
PRINT 'The database updated succeeded'
COMMIT TRANSACTION
END
ELSE PRINT 'The database update failed'
GO
DROP TABLE #tmpErrors
GO
